将项添加到索引:QuerySet无属性保存

时间:2017-03-09 05:36:28

标签: python django elasticsearch

我试图在更改时将一个字段添加到我的索引中。

以下代码正确更新索引,但实际模型不会更新。另外,我收到了一个追溯错误(通过底部的链接提供)。

我收到错误: 'QuerySet' object has no attribute 'save'

我通过以下链接提供了追溯。

#models.py

class Tag(models.Model):
    name = models.CharField("Name", max_length=5000, blank=True)
    taglevel = models.IntegerField("Tag level", null=True, blank=True)

    def to_search(self):
        tags = self.id
        if tags:
            queryset = Item.objects.filter(tag=tags)
            for object in queryset:
                object.save()
        return queryset

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.get_grouped_tags(),
            "title": self.title
        }
        return ItemIndex(meta={'id': self.id}, **d)

    def indexing(self):
        obj = ItemIndex(
            meta={'id': self.id},
            title=self.title,
            tag=self.get_grouped_tags(),
        )
        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.tag.through)

#search.py​​

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

回溯

http://dpaste.com/1FGGKBF

1 个答案:

答案 0 :(得分:0)

问题是信号执行此行

instance.to_search().save()

但是对于您的Tag模型to_search返回查询集

def to_search(self):
    tags = self.id
    if tags:
        queryset = Item.objects.filter(tag=tags)
        for object in queryset:
            object.save()
    return queryset #  <- here

这就是您收到此错误的原因。您应该像ItemIndex模型Item一样返回to_search,或者返回自己。