2014-12-24 86 views
0

我正在使用Django Haystack。 這裏是我的代碼:更新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,使其在帖子實例創建或更新索引。並且它實際上在創建時索引實例,除了使用準備方法的image_url字段。它通過實例更新進行索引。

問題是爲什麼它沒有被創建索引?

任何指針表示讚賞。

回答

2

我結束了自定義的信號處理器,就像這樣:

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' 
相關問題