我正在使用Django Haystack。 这是我的代码:
settings.py
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
search_indexes.py
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
owner = indexes.CharField(model_attr='owner')
image_url = indexes.CharField()
def get_model(self):
return Post
def prepare_image_url(self, obj):
# Get first images for resulted search objects
return [image.image_main_page.url for image in obj.images.order_by('id')[:1]]
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
如您所见,我使用RealtimeSignalProcessor使其成为Post实例创建或更新的索引。它实际上会在创建时为实例编制索引,除了使用prepare方法的 image_url 字段。它在实例更新时编入索引。
问题是为什么它没有被创作索引?
任何指针都表示赞赏。
答案 0 :(得分:3)
我最终选择了自定义信号处理器:
class RelatedRealtimeSignalProcessor(RealtimeSignalProcessor):
"""
Extension to haystack's RealtimeSignalProcessor not only causing the
search_index to update on saved model, but also for image url, which is needed to show
images on search results
"""
def handle_save(self, sender, instance, **kwargs):
if hasattr(instance, 'reindex_related'):
for related in instance.reindex_related:
related_obj = getattr(instance, related)
self.handle_save(related_obj.__class__, related_obj)
return super(RelatedRealtimeSignalProcessor, self).handle_save(sender, instance, **kwargs)
def handle_delete(self, sender, instance, **kwargs):
if hasattr(instance, 'reindex_related'):
for related in instance.reindex_related:
related_obj = getattr(instance, related)
self.handle_delete(related_obj.__class__, related_obj)
return super(RelatedRealtimeSignalProcessor, self).handle_delete(sender, instance, **kwargs)
在设置中指出:
HAYSTACK_SIGNAL_PROCESSOR = 'your_app.signals.RelatedRealtimeSignalProcessor'