How to make a Django custom management command argument not required?

前端 未结 2 780
梦谈多话
梦谈多话 2021-02-18 19:01

I am trying to write a custom management command in django like below-

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argum         


        
2条回答
  •  别那么骄傲
    2021-02-18 19:40

    You can use the dash syntax for optional keyword arguments:

    class Command(BaseCommand):
    
        def add_arguments(self, parser):
            parser.add_argument("-d", "--delay", type=int)
    
        def handle(self, *args, **options):
            delay = options["delay"] if options["delay"] else 21
            print(delay)
    

    Use:

    $ python manage.py mycommand -d 4
    4
    $ python manage.py mycommand --delay 4
    4
    $ python manage.py mycommand
    21
    

    Docs:

    https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/#s-accepting-optional-arguments

    Simple explanation:

    https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html#handling-arguments

提交回复
热议问题