使用信号索引模型反向M2M

时间:2017-04-18 21:51:00

标签: python django elasticsearch-py

我已经遵循了许多示例和文档,但无法做到这一点。

每当我更新模型时,我都会尝试制作我的Elasticsearch索引。使用'autoindex'不会记录M2M。

  1. 当我更改Tag内的值时,它应该更新所有Items所在的索引
  2. 我正在使用django-elasticsearchhere),它是elasticsearch-py的包装。

    当我尝试connect(tag_index, sender=Tag.item.through)时,它无法找到标签,因为它尚未被模型导入。

    这是如何正确实现的?

    class Tag(models.Model):
        name = models.CharField(max_length=500, blank=True)
        taglevel = models.IntegerField(null=True, blank=True)
    
    def tag_index(instance, **kwargs):
        Task.instance.es.do_index()
    
    class Item(EsIndexable, models.Model):
        title = models.CharField(max_length=100, blank=True)
        tag = models.ManyToManyField('Tag', blank=True)
    
        class Elasticsearch(EsIndexable.Elasticsearch):
            serializer_class = TaskEsSerializer
            fields = ['title', 'tag']
    
    @receiver(post_save, sender= Task)
    def index_elastic(instance, **kwargs):
        instance.es.do_index()
    
    m2m_changed.connect(tag_index, sender=Item.tag.through)
    

1 个答案:

答案 0 :(得分:0)

好的,它不是" smart"我以为是。您需要参考每个模型中的函数

class Tag(models.Model):
    name = models.CharField(max_length=500, blank=True)
    taglevel = models.IntegerField(null=True, blank=True)

@receiver(post_save, sender= Tag)
@receiver(post_delete, sender= Tag)
def index_tag(instance, **kwargs):
    Item.objects.get().es.do_index()

def tag_index(instance, **kwargs):
    instance.es.do_index()

class Item(EsIndexable, models.Model):
    title = models.CharField(max_length=100, blank=True)
    tag = models.ManyToManyField('Tag', blank=True)

    class Elasticsearch(EsIndexable.Elasticsearch):
        serializer_class = ItemEsSerializer
        fields = ['title', 'tag']

@receiver(post_save, sender= Item)
def index_elastic(instance, **kwargs):
    instance.es.do_index()