如何使 Django 自定义管理命令参数不需要?

2022-01-23 00:00:00 python django command

问题描述

我正在尝试在 django 中编写一个自定义管理命令,如下所示-

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

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('delay', type=int)

    def handle(self, *args, **options):
        delay = options.get('delay', None)
        print delay

现在,当我运行 python manage.py mycommand 12 时,它会在控制台上打印 12.这很好.

Now when I am running python manage.py mycommand 12 it is printing 12 on console. Which is fine.

现在,如果我尝试运行 python manage.py mycommand 然后我想要,该命令默认在控制台上打印 21.但它给了我这样的东西-

Now if I try to run python manage.py mycommand then I want that, the command prints 21 on console by default. But it is giving me something like this-

usage: manage.py mycommand [-h] [--version]
                           [-v {0,1,2,3}]
                           [--settings SETTINGS]
                           [--pythonpath PYTHONPATH]
                           [--traceback]
                           [--no-color]
                           delay

那么现在,如果没有给出值,我应该如何使命令参数不需要"并取默认值?

So now, how should I make the command argument "not required" and take a default value if value is not given?


解决方案

文档 建议:

对于 nargs 等于 ?* 的位置参数,当不存在命令行参数时使用 default 值.

For positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present.

所以下面应该可以解决问题(如果提供,它将返回值,否则返回默认值):

So following should do the trick (it will return value if provided or default value otherwise):

parser.add_argument('delay', type=int, nargs='?', default=21)

用法:

$ ./manage.py mycommand
21
$ ./manage.py mycommand 4
4

相关文章