【问题标题】:Where in Django can I run startup code that requires models?在 Django 中,我可以在哪里运行需要模型的启动代码?
【发布时间】:2019-06-01 00:31:04
【问题描述】:

在 Django 启动时,我需要运行一些需要访问数据库的代码。我更喜欢通过模型来做到这一点。

这是我目前在apps.py 中拥有的内容:

from django.apps import AppConfig
from .models import KnowledgeBase

class Pqawv1Config(AppConfig):
    name = 'pqawV1'

    def ready(self):
        to_load = KnowledgeBase.objects.order_by('-timestamp').first()
        # Here should go the file loading code

但是,这会产生以下异常:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

那么在模型初始化之后,Django中有没有地方可以运行一些启动代码呢?

【问题讨论】:

  • from .models import KnowledgeBase 移入 def ready 方法。这里在 header 中导入会导致模型加载过早。
  • @WillemVanOnsem,这行得通,谢谢。但是这个解决方案有多好?有什么副作用?我对 Python 很陌生...
  • 不同的是,当配置调用ready时,您只需导入.models,因此您推迟导入。正是由于“急切”的导入导致了麻烦。

标签: python django database django-models startup


【解决方案1】:

问题是您在文件顶部导入.models。这意味着,当文件app.py 文件被加载时,Python 将在评估该行时加载models.py 文件。但这为时过早。您应该让 Django 正确加载。

你可以在def ready(self)方法中移动导入,这样当ready()被Django框架调用时,models.py文件就会被导入,比如:

from django.apps import AppConfig

class Pqawv1Config(AppConfig):
    name = 'pqawV1'

    def ready(self):
        from .models import KnowledgeBase
        to_load = KnowledgeBase.objects.order_by('-timestamp').first()
        # Here should go the file loading code

【讨论】:

  • 一旦ready()中加载了数据或资源,我们如何在views中使用它们?导入应用配置?
  • @advocado:您可以使用from django.apps import apps 获取给定应用的appconfig; apps.get_app_config('app_name')。如果您存储加载在self(即self.to_load = ...)上的资源,则可以使用apps.get_app_config('app_name').to_load 访问它。但是您应该在函数中执行此操作,因为模型是在 触发 ready 函数之前加载的。
  • 很好(也很简洁)的答案!
  • 顺便说一句,from .models import * 会失败(“SyntaxError: import * only allowed at module level”)而from .models import KnowledgeBase 会成功
猜你喜欢
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多