我正在努力学习信号。在下面的apps.py中有几条注释行。一旦我从.models取消注释导入ReceiverModel,SenderModel,我就会得到django.core.exceptions.AppRegistryNotReady:尚未加载应用程序。
你能帮我理解我做错了什么吗?
demo_signals / my_app应用/ models.py
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class SenderModel(models.Model):
pass
class ReceiverModel(models.Model):
pass
@receiver(post_save, sender=SenderModel)
def my_callback(self, sender, **kwargs):
print("Saving finished!")
demo_signals / demo_signals / settings.py
INSTALLED_APPS = [
...
'my_app.apps.MyAppConfig',
]
demo_signals / my_app应用/ apps.py
from django.apps import AppConfig
from django.db.models.signals import Signal
#from .models import ReceiverModel, SenderModel
class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
print("Here")
#Signal.connect(self, ReceiverModel, SenderModel)
追溯的某些部分
File "/home/michael/workspace/demo_signals/my_app/apps.py", line 3, in <module>
from .models import ReceiverModel, SenderModel
File "/home/michael/workspace/demo_signals/my_app/models.py", line 5, in <module>
class SenderModel(models.Model):
File "/home/michael/workspace/PhotoArchive/venv/lib/python3.5/site-packages/django/db/models/base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/michael/workspace/PhotoArchive/venv/lib/python3.5/site-packages/django/apps/registry.py", line 240, in get_containing_app_config
self.check_apps_ready()
File "/home/michael/workspace/PhotoArchive/venv/lib/python3.5/site-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
答案 0 :(得分:1)
根据the docs,您无法在AppConfig
中导入模型,而是需要执行此操作:
class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
ReceiverModel = self.get_model('ReceiverModel')
SenderModel = self.get_model('SenderModel')
Signal.connect(self, ReceiverModel, SenderModel)