liveBook · Manning

Handle()

As explained in Django in Action

The BaseCommand method that Django invokes to perform a management command's action.

handle() is the entry point Django invokes when a custom management command runs. Define it on a BaseCommand subclass, accept *args and **options, perform the command’s work, and write output through self.stdout.write(). section 9.2 section 9.6

Listing 9.2 A management command that displays the Musician objects in the database
# RiffMates/bands/management/commands/musicians.py
from django.core.management.base import BaseCommand
from bands.models import Musician

class Command(BaseCommand): #1
    help = "Lists registered musicians"  #2

    def handle(self, *args, **options): #3
        for musician in Musician.objects.all():  #4
            self.stdout.write( #5
                f"{musician.last_name}, {musician.first_name}"
            )

A complete musicians command shows handle() querying Musician objects and formatting each result for command-line output. section 9.2

Listing musicians

In bands/management/commands/musicians.py, Command.handle() loops through Musician.objects.all() and writes each musician as “last name, first name.” Running python manage.py musicians produces one musician per line. Django also uses the class’s help attribute for manage.py musicians --help. section 9.2 section 9.6

How Django in Action covers it

How deep it goes
Explains the entry point, *args and **options, database work, output proxies, and command-line argument flow.
Examples
Demonstrates a musicians command that queries Musician objects and prints formatted names.
What it assumes
Assumes Python classes and Django app structure while teaching the management/commands layout and BaseCommand inheritance.
What you can do after
Build a Django management command that performs work, accepts parsed options, and emits testable output.
How it connects
Connects handle() with BaseCommand, self.stdout.write(), add_arguments(), argparse, CommandError, and call_command().

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.