在导入应用程序的设置中调用的信号:失败
Signal called in settings importing an app : failed
我正在使用 Python 3.4.3
、Django 1.9.2
和 django-haystack 2.4.1
。
我只放了必要的代码来说明。
这是我的设置:
INSTALLED_APPS = (
...,
contacts.documents,
haystack,
contacts.search,
)
HAYSTACK_SIGNAL_PROCESSOR = 'contacts.search.signals.MyRealtimeProcessor'
这是我的文件:contacts.search.signals.py :
from contacts.documents.models import Document
class MyRealtimeProcessor(RealtimeSignalProcessor):
def handle_save(self, sender, instance, **kwargs):
…
d_index = self.connections[using].get_unified_index()\
.get_index(Document)
使用这段代码我得到了错误 :
raise AppRegistryNotReady("Apps aren't loaded yet.")
因为 from contacts.documents.models import Document
在我的信号中。
我该如何更正它?
在 Django 加载完所有应用程序之前,您无法加载模型。我不完全清楚为什么你的 signals.py
文件在加载应用程序之前被导入,但你可以通过将此逻辑移动到 class 的 __init__
方法中来解决这个问题:
def __init__(self, *args, **kwargs):
from contacts.documents.models import Document
self.document_model = Document
super(MyRealtimeProcessor, self).__init__(args, kwargs)
然后在 handle_save
:
d_index = self.connections[using].get_unified_index()\
.get_index(self.document_model)
我正在使用 Python 3.4.3
、Django 1.9.2
和 django-haystack 2.4.1
。
我只放了必要的代码来说明。
这是我的设置:
INSTALLED_APPS = (
...,
contacts.documents,
haystack,
contacts.search,
)
HAYSTACK_SIGNAL_PROCESSOR = 'contacts.search.signals.MyRealtimeProcessor'
这是我的文件:contacts.search.signals.py :
from contacts.documents.models import Document
class MyRealtimeProcessor(RealtimeSignalProcessor):
def handle_save(self, sender, instance, **kwargs):
…
d_index = self.connections[using].get_unified_index()\
.get_index(Document)
使用这段代码我得到了错误 :
raise AppRegistryNotReady("Apps aren't loaded yet.")
因为 from contacts.documents.models import Document
在我的信号中。
我该如何更正它?
在 Django 加载完所有应用程序之前,您无法加载模型。我不完全清楚为什么你的 signals.py
文件在加载应用程序之前被导入,但你可以通过将此逻辑移动到 class 的 __init__
方法中来解决这个问题:
def __init__(self, *args, **kwargs):
from contacts.documents.models import Document
self.document_model = Document
super(MyRealtimeProcessor, self).__init__(args, kwargs)
然后在 handle_save
:
d_index = self.connections[using].get_unified_index()\
.get_index(self.document_model)