2

How would you create a Django management command that has arguments that are dynamic depending on a positional argument?

For example, the named arguments for the command dynamic_command with positional argument option1:

python manage.py dynamic_command option1

should be different from the named arguments for the command dynamic_command with positional argument option2:

python manage.py dynamic_command option2

This is useful for cases where the underlying command handle is the same, but parameters could vary depending on the context that the command is run.

To elaborate further, you may want the command dynamic_command option1 to accept named arguments --kv1 --kv2:

e.g.

python manage.py dynamic_command option1 --kv1 --kv2

but dynamic_command option2 to accept named arguments --kv3 --kv4:

e.g.

python manage.py dynamic_command option2 --kv3 --kv4
Nick Falco
  • 207
  • 2
  • 10

1 Answers1

1

Override the add_arguments(self, parser) method. the parser argument is an argparse.ArgumentParser object (docs: https://docs.python.org/3/library/argparse.html).

You might be looking for Sub-commands/sub-parsers: https://docs.python.org/3/library/argparse.html#sub-commands

thebjorn
  • 26,297
  • 11
  • 96
  • 138
  • Thanks! I think I can override the add_arguments method and do something like this using sub-parsers: https://stackoverflow.com/questions/10448200/how-to-parse-multiple-nested-sub-commands-using-python-argparse – Nick Falco Jul 12 '21 at 01:22