django-admin 自定义命令中的两个参数 [英] Two arguments in django-admin custom command
问题描述
我有一个 工作 django-admin 自定义命令,我用它来用新信息填充我的数据库.同样,一切正常.
I have a working django-admin custom command that I use to populate my database with new information. Again, everything works.
但是,我现在稍微改变了我的模型和函数,以接受两个参数作为元组 - 名字 和 姓氏,而不仅仅是姓名".
However, I have now changed my models and function slightly to accept two arguments as a tuple - first name and last name, instead of just "name".
下面的以前的代码 - 工作.使用manage.py xyz name1 name2 name3... 等(不同参数之间的空格)运行
Previous code below - working. Run using "manage.py xyz name1 name2 name3... etc. (space between the different args)
from django.core.management.base import BaseCommand, CommandError
from detail.models import ABC
from detail.parser import DEF
class Command(BaseCommand):
args = '<name...>'
help = 'Populates the ABC class database'
def handle(self, *args, **options):
for symbol in args:
try:
info = DEF(name)
是否可以从 django-admin 自定义命令传递两个参数,其中第二个参数是可选的 --> 即 (first, last=None)?
下面是我想使用的伪代码......manage.py xyz (first1, last1) (first2, last2) <-- 或者这个的一些变体
Pseudocode below of what I'd like to run using... "manage.py xyz (first1, last1) (first2, last2) <-- or some variation of this
我已经更改了函数 DEF 以适当地接受它作为独立函数.我只是不确定现在如何让 django-admin 命令工作.
I've already changed the function DEF to accept this appropriately as a standalone function. I'm just not sure how I can get the django-admin command working now.
推荐答案
这完全有可能,尽管 django.core.management
没有提供一个特定的工具来做到这一点.您可以解析通过 args
关键字参数传递的参数.为此,您必须想出一个语法(在命令的 help
属性中定义语法可能是个好主意).
It's entirely possible, although django.core.management
does not provide a specific tool to do so. You can parse the arguments passed via the args
keyword argument. You'll have to come up with a syntax for doing so (defining the syntax in the help
attribute of the command would probably be a good idea).
假设语法是firstname.lastname
,或者在省略姓氏的情况下只是firstname
,你可以这样做:
Assuming the syntax is firstname.lastname
, or just firstname
in the case that the last name is omitted, you can do something like:
def handle(self, *args, **options):
for arg in args:
try:
first_name, last_name = arg.split('.')
except ValueError:
first_name, last_name = arg, None
info = DEF(first_name, last_name)
命令的用户可以像这样传递参数:
And users of the command can pass in arguments like so:
$ python manage.py yourcommand -v=3 john.doe bill patrick.bateman
这篇关于django-admin 自定义命令中的两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!