初始化数据库,如下两种方案,可以同时使用
方案一:
https://docs.djangoproject.com/zh-hans/4.0/howto/initial-data/
方案二:
https://docs.djangoproject.com/zh-hans/4.0/howto/custom-management-commands/
必须定义 Command 类,该类继承自 BaseCommand
polls/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
_private.py
closepoll.py
tests.py
views.py
自定义管理命令
python manage.py closepoll <poll_ids>
polls/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
_private.py
closepoll.py
tests.py
views.py
from django.core.management.base import BaseCommand, CommandError
from polls.models import Question as Poll
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def add_arguments(self, parser):
parser.add_argument('poll_ids', nargs='+', type=int)
def handle(self, *args, **options):
for poll_id in options['poll_ids']:
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise CommandError('Poll "%s" does not exist' % poll_id)
poll.opened = False
poll.save()
self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
必选参数
def add_arguments(self, parser):
parser.add_argument('poll_ids', nargs='+', type=int)
必选参数的使用
def handle(self, *args, **options):
poll_ids = options['poll_ids']
可选参数
def add_arguments(self, parser):
parser.add_argument(
'--delete',
action='store_true',
help='Delete poll instead of closing it',
)
可选参数的使用
def handle(self, *args, **options):
# ...
if options['delete']:
poll.delete()
输出到控制台时使用self.stdout.write
代替print
self.stdout.write("Unterminated line")
注意
当add_argument
方法增加的参数名中包含连字符时,例如:
parser.add_argument(
'--force-color', action='store_true',
help='Force colorization of the command output.',
)
在handle
方法中使用时,应该将连字符转为下划线,例如:
options['force_color']
相关文档
Argparse 教程
https://docs.python.org/zh-cn/3/howto/argparse.html
Argparse API
https://docs.python.org/zh-cn/3/library/argparse.html
add_argument方法
https://docs.python.org/zh-cn/3/library/argparse.html#the-add-argument-method