2017-03-01 64 views
0

此代碼應該在每次創建新對象時將項目添加到索引。它有效,但沒有意識到正在創建M2M領域。在M2M字段上觸發Post_save信號

我相信信號不會「看」標籤(因爲它是一個M2M領域)。

換句話說:

  • 添加標題字段只索引當對象被「創造」

  • 只有「保存」被點擊時增加了M2M關係指數

FWIW,這是索引彈性搜索。

Models.py

class Item(models.Model): 
    title = models.CharField("Title", max_length=10000, blank=True) 
    tag = models.ManyToManyField('Tag', blank=True) 

    def get_grouped_tags(self): 
     tag = self.tag.order_by('taglevel') 
     grouped_tags = { 
      tag_level: [ 
       { 'name': tag_of_level.name, 'taglevel': tag_of_level.taglevel, } 
       for tag_of_level in tags_of_level 
      ] for tag_level, tags_of_level 
      in groupby(tag, lambda tag: tag.taglevel) 
     } 
     return grouped_tags 

    def to_search(self): 
     d = { 
      "tags": self.grouped_tags(), 
      "title": self.title 
     } 
     return ItemIndex(meta={'id': self.id}, **d) 

    def indexing(self): 
     obj = ItemIndex(
      meta={'id': self.id}, 
      title=self.title, 
      typeItem=self.get_typeItem_display() 
     ) 
     obj.save() 
     return obj.to_dict(include_meta=True) 

def update_search(instance, **kwargs): 
    instance.to_search().save() 

def remove_from_search(instance, **kwargs): 
    instance.to_search().delete() 

post_save.connect(update_search, sender=Item) 
post_save.connect(update_search, sender=Tag) 
pre_delete.connect(remove_from_search, sender=Item) 
pre_delete.connect(remove_from_search, sender=Tag) 
m2m_changed.connect(update_search, sender=Item) 

Search.py​​

connections.create_connection() 

class ItemIndex(DocType): 
    title = String() 
    class Meta: 
     index = 'Item-index' 


def bulk_indexing(): 
    ItemIndex.init() 
    es = Elasticsearch() 
    bulk(client=es, actions=(b.indexing() for b in models.Item.objects.all().iterator())) 


def _search(title): 
    s = Search().filter('term', title=title.text) 
    response = s.execute() 
    return response 

回答

0

明白了!與m2m_changed有關。我需要創建一個「通過」方法。

只需要改變的是:

m2m_changed.connect(update_search, sender=Item.tag.through)