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

2023-10-19Python开发问题
3

本文介绍了如何使 Django 自定义管理命令参数不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试在 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

这篇关于如何使 Django 自定义管理命令参数不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10