For my recent project pyremote, I needed to run a script every night to remove old job postings from the database. I decided to implement it as a custom manage.py command so that I can easily run it from command line and add it to a nightly cron job on the server.
To create a custom command you need to add a
management directory to your Django app. In there create another directory called
commands and in that one add a Python file and call it the way you want the command to be called. In my case I called it
The Python file you create must define a class called
Command that inherits from
BaseCommand. Create a method named
handle in your
Command class. The actual logic of the command goes in this method.
You can also define
add_argument method where you specify any command line arguments you would like to pass to the custom command when you invoke it. These arguments are then available to the
handle method in a dictionary called
Now I can run this command to clean the database from jobs that are added to the page more than 30 days ago: