Python Django 管理命令参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27611468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:01:04  来源:igfitidea点击:

Django Management Command Argument

pythondjango

提问by Peter Graham

I need to pass in an integer argument to a base command in Django. For instance if my code was

我需要将整数参数传递给 Django 中的基本命令。例如,如果我的代码是

from django.core.management import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options, number_argument):
        square = number_argument ** 2
        print square

I would want to say python manage.py square_command 4 and have it return 16. Is there a way I can pass an argument through the terminal to the command I want to run?

我想说 python manage.py square_command 4 并让它返回 16。有没有办法可以通过终端将参数传递给我想运行的命令?

采纳答案by acidjunk

Add this method to your Command class:

将此方法添加到您的 Command 类:

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

You can then use your option in the code, like this:

然后您可以在代码中使用您的选项,如下所示:

def handle(self, *args, **options):
    my_int_argument = options['my_int_argument']

The benefit of doing it this way is that the helpoutput is automatically generated for manage.py my_command --help

这样做的好处是help输出是自动生成的manage.py my_command --help

回答by mipadi

Yes. The mechanism for doing so is described here, but basically, you can get the argument from args[0].

是的。这里描述了这样做的机制,但基本上,您可以从args[0].