2

Is there anyway to create nested management commands in Django, similar to what the docker and kubectl have? For example, let's say I need to have the following structure:

|-->manage.py
    |-->restaurant
        |-->list
        |-->get
    |-->employee
        |-->list
        |-->get
        |-->delete

The following commands should all be possible:

./manage.py -h
./manage.py restaurant -h
./manage.py restaurant list
./manage.py employee list
./manage.py restaurant get ""
./manage.py employee delete tiffany

The argparse subparser looks promising but I feel like there should be an easier way using python modules in the app/management/commands or something like that.

Johnny Metz
  • 5,977
  • 18
  • 82
  • 146

1 Answers1

0

You can add an argument for that.

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('command_type', type=str)

    def handle(self, *args, **options):
        command_type = options['command_type']
        if command_type == 'list':
            # list command
            return
        elif command_type == 'get':
            # get command
            return
        raise CommandError('Invalid arguemnt for command_type')

Usage:

py manage.py my_command get
py manage.py my_command list
Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27