【问题标题】:Is it possible to populate models with fixtures in AppConfig's ready() method?是否可以在 AppConfig 的 ready() 方法中使用固定装置填充模型?
【发布时间】:2020-04-16 18:04:47
【问题描述】:

我正在尝试在启动 Django 后从固定装置填充模型。

我发现,可以在AppConfigready() 方法中调用自定义方法。

所以,当我尝试下一步时:

class ApplicationConfig(AppConfig):
    name = 'application'

    def ready(self):
        from django.core.management import call_command
        call_command('loaddata', 'application/fixtures/some_info.json')

我收到错误消息:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
    django.setup()
  File "/app/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/app/venv/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate
    raise RuntimeError("populate() isn't reentrant")
RuntimeError: populate() isn\'t reentrant

还有其他方法可以在启动时预填充模型吗?或者,如何解决我的问题?

【问题讨论】:

  • 我不会,因为唯一有用的情况是在运行测试时,并且已经在那里实现了。您的数据存储是否如此短暂以至于您有这种担忧?

标签: django model initialization


【解决方案1】:

Use migrations file..

在该函数中,只需执行常规 Mymodel.objects.create(yadayadayada...)

确保首先创建一个 EMPTY 迁移文件,因为您需要先在 db 中创建表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多