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
