Django Management Commands Creating and Running a Management Command


To perform actions in Django using commandline or other services (where the user/request is not used), you can use the management commands.

Django modules can be imported as needed.

For each command a separate file needs to be created: myapp/management/commands/
(The management and commands directories must have an empty file)

from import BaseCommand, CommandError

# import additional classes/modules as needed
# from myapp.models import Book

class Command(BaseCommand):
    help = 'My custom django management command'

    def add_arguments(self, parser):
       parser.add_argument('book_id', nargs='+', type=int)
       parser.add_argument('author' , nargs='+', type=str)

    def handle(self, *args, **options):
       bookid = options['book_id'] 
       author = options['author']
       # Your code goes here
        # For example:
        # books = Book.objects.filter(author="bob")
        # for book in books:
        # = "Bob"

Here class name Command is mandatory which extends BaseCommand or one of its subclasses.

The name of the management command is the name of the file containing it. To run the command in the example above, use the following in your project directory:

python my_command

Note that starting a command can take a few second (because of the import of the modules). So in some cases it is advised to create daemon processes instead of management commands.

More on management commands