在Django管理员自定义命令两个参数 [英] Two arguments in django-admin custom command
问题描述
我有一个工作 Django的管理员自定义的,我用填充我的新的信息的数据库命令。再次,一切正常。
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".
previous code以下 - 工作。通过运行manage.py XYZ名1名2 NAME3 ...等(不同ARGS之间的空间)
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的管理员自定义命令,其中第二个参数是可选的? - >即(第一,最后=无)
伪code以下的东西,我想用跑......manage.py XYZ(first1,last1)(first2,last2)LT; - 或者这一些变化
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
关键字参数传递的参数。你必须要拿出这样做的语法(定义在帮助语法
命令的属性,可能会是一个好主意)。
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
,或只是姓
在省略了姓氏的情况下,你可以这样做:
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管理员自定义命令两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!