liveBook · Manning

Add_argument

As explained in Django in Action

add_argument() is an argparse parser method that defines one positional argument or flag and its parsing options.

add_argument() registers one command-line argument with an argparse parser. In a Django management command, call it inside add_arguments(), where BaseCommand supplies the parser. section 9.3

Configure each argument by supplying:

  • A name: use leading dashes for a flag such as --last_name; omit them for a positional argument. section 9.3
  • An optional short form, such as -l, followed by options including help text, defaults, and type conversion. section 9.3
  • With only a name and help, the argument expects a string value after the flag. section 9.3

Filtering musicians

A musicians command can register --last_name/-l, --first_name/-f, and --birth/-b. Running python manage.py musicians --last_name Loblaw passes the value through options, where handle() can use it for filtering.

How Django in Action covers it

How deep it goes
Explains names, short forms, help text, string values, and broader parser options without detailing all eleven parameters.
Examples
Demonstrates musician filters using last-name, first-name, and birth-date flags.
What it assumes
Builds on argparse terminology while receiving the parser automatically through BaseCommand.add_arguments().
What you can do after
Apply it via argparse in a Django management command to accept filter values from the shell.
How it connects
Connects argparse, Django management commands, BaseCommand, and handle() options.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.