Python Django自定义管理命令-为参数添加默认值
我使用的是Django 2.2,我想写一篇文章来添加一个自定义任务(对于应用程序),将装置加载到数据库表中 这就是我到目前为止所做的:Python Django自定义管理命令-为参数添加默认值,python,django,Python,Django,我使用的是Django 2.2,我想写一篇文章来添加一个自定义任务(对于应用程序),将装置加载到数据库表中 这就是我到目前为止所做的: from django.core.management.base import BaseCommand from django.core import management class Command(BaseCommand): help = 'Generate Capture Data from loaded fixtures' def
from django.core.management.base import BaseCommand
from django.core import management
class Command(BaseCommand):
help = 'Generate Capture Data from loaded fixtures'
def add_arguments(self, parser):
parser.add_argument('definitions', type=str, help='Name of the definitions fixtures file', default='definitions.json')
parser.add_argument('sections', type=str, help='Name of the sections fixtures file', default='sections.json')
parser.add_argument('questions', type=str, help='Name of the questions fixtures file', default='questions.json')
def handle(self, *args, **kwargs):
print(kwargs)
但是,当我运行python manage.py generate_data
时,会引发以下异常:
usage: manage.py generate_data [-h] [--version] [-v {0,1,2,3}]
[--settings SETTINGS]
[--pythonpath PYTHONPATH] [--traceback]
[--no-color] [--force-color]
definitions sections questions
manage.py generate_data: error: the following arguments are required: definitions, sections, questions
为什么我为add_arguments()
提供的默认值被忽略?您可能需要使用。根据文件,其中一种情况是:
“?”。如果可能,将从命令行使用一个参数,并作为单个项生成。如果不存在命令行参数,将生成默认值
因此,代码将是:
parser.add_argument('definitions', nargs='?', type=str, help='Name of the definitions fixtures file', default='definitions.json')
parser.add_argument('sections', nargs='?', type=str, help='Name of the sections fixtures file', default='sections.json')
parser.add_argument('questions', nargs='?', type=str, help='Name of the questions fixtures file', default='questions.json')