Monday, June 21, 2021

What is DJango call_command

To call a management command from code use call_command.


django.core.management.call_command(name*args**options)


the name of the command to call or a command object. Passing the name is preferred unless the object is required for testing.


*args

a list of arguments accepted by the command. Arguments are passed to the argument parser, so you can use the same style as you would on the command line. For example, call_command('flush', '--verbosity=0').



**options

named options accepted on the command-line. Options are passed to the command without triggering the argument parser, which means you’ll need to pass the correct type. For example, call_command('flush', verbosity=0) (zero must be an integer rather than a string).

Examples:



from django.core import management

from django.core.management.commands import loaddata


management.call_command('flush', verbosity=0, interactive=False)

management.call_command('loaddata', 'test_data', verbosity=0)

management.call_command(loaddata.Command(), 'test_data', verbosity=0)



Note that command options that take no arguments are passed as keywords with True or False, as you can see with the interactive option above.

Named arguments can be passed by using either one of the following syntaxes:


Some command options have different names when using call_command() instead of django-admin or manage.py. For example, django-admin createsuperuser --no-input translates to call_command('createsuperuser', interactive=False). To find what keyword argument name to use for call_command(), check the command’s source code for the dest argument passed to parser.add_argument().


Output redirection


with open('/path/to/command_output', 'w') as f:

    management.call_command('dumpdata', stdout=f)



No comments:

Post a Comment