初始化数据库,如下两种方案,可以同时使用
方案一:
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

  1. polls/
  2. __init__.py
  3. models.py
  4. management/
  5. __init__.py
  6. commands/
  7. __init__.py
  8. _private.py
  9. closepoll.py
  10. tests.py
  11. views.py

自定义管理命令

  1. python manage.py closepoll <poll_ids>
  1. polls/
  2. __init__.py
  3. models.py
  4. management/
  5. __init__.py
  6. commands/
  7. __init__.py
  8. _private.py
  9. closepoll.py
  10. tests.py
  11. views.py
  1. from django.core.management.base import BaseCommand, CommandError
  2. from polls.models import Question as Poll
  3. class Command(BaseCommand):
  4. help = 'Closes the specified poll for voting'
  5. def add_arguments(self, parser):
  6. parser.add_argument('poll_ids', nargs='+', type=int)
  7. def handle(self, *args, **options):
  8. for poll_id in options['poll_ids']:
  9. try:
  10. poll = Poll.objects.get(pk=poll_id)
  11. except Poll.DoesNotExist:
  12. raise CommandError('Poll "%s" does not exist' % poll_id)
  13. poll.opened = False
  14. poll.save()
  15. self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))

必选参数

  1. def add_arguments(self, parser):
  2. parser.add_argument('poll_ids', nargs='+', type=int)

必选参数的使用

  1. def handle(self, *args, **options):
  2. poll_ids = options['poll_ids']

可选参数

  1. def add_arguments(self, parser):
  2. parser.add_argument(
  3. '--delete',
  4. action='store_true',
  5. help='Delete poll instead of closing it',
  6. )

可选参数的使用

  1. def handle(self, *args, **options):
  2. # ...
  3. if options['delete']:
  4. poll.delete()

输出到控制台时使用self.stdout.write代替print

  1. self.stdout.write("Unterminated line")

注意

add_argument方法增加的参数名中包含连字符时,例如:

  1. parser.add_argument(
  2. '--force-color', action='store_true',
  3. help='Force colorization of the command output.',
  4. )

handle方法中使用时,应该将连字符转为下划线,例如:

  1. 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