每次创建新对象时,此代码都应将项添加到索引中。它有效,但没有意识到正在创建M2M字段。
我相信信号没有"看到"标签(因为它是一个M2M字段)。
换句话说:
仅在对象为" CREATED"
仅在" SAVE"时将M2M关系添加到索引。点击
FWIW,这是弹性搜索的索引。
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)
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 :(得分:0)
知道了!与m2m_changed
有关。我需要创建一个"通过"方法
只需更改:
m2m_changed.connect(update_search, sender=Item.tag.through)