加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

django – 使用update_index –remove从Haystack / Xapian索引中

发布时间:2020-12-20 11:20:02 所属栏目:Python 来源:网络整理
导读:我正在尝试使用./manage.py update_index –remove管理命令从搜索索引中删除结果. 我想删除这些对象,而不是删除它们时,只是在它们的时候: enabled = models.BooleanField() 字段是假的 我该怎么办?我还需要准备SearchIndex吗? import datetimefrom haysta
我正在尝试使用./manage.py update_index –remove管理命令从搜索索引中删除结果.

我想删除这些对象,而不是删除它们时,只是在它们的时候:

enabled = models.BooleanField()

字段是假的

我该怎么办?我还需要准备SearchIndex吗?

import datetime
from haystack.indexes import *
from haystack import site
from articles.models import Article

class ArticleIndex(SearchIndex):

    text = CharField(document=True,use_template=True)
    title = CharField(model_attr='title')
    content = CharField(model_attr='content')

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Article.site_published_objects.filter(enabled=True)

    def get_updated_field(self):
        return 'modified'

    def remove_object(self):
        pass

site.register(Article,ArticleIndex)

谢谢.

解决方法

我没有对此进行测试,但您可以通过将搜索索引模板包装在一个条件中来实现所需的效果,例如:

{# in search/indexes/yourapp/article_text.txt #}
{% if object.enabled %}
    {# ... whatever you have now #}
{% endif %}

运行./manage.py update_index时,启用了= False的文章最终将没有与之关联的数据,也不会显示在搜索中.

更新

查看SearchIndex的源代码,有一个用于从索引中删除对象的remove_object()方法.还有运行should_update()以确定是否应更新对象的索引.

也许可以使用以下方法触发索引删除:

class ArticleIndex(SearchIndex):
    # ...

    def should_update(self,instance,**kwargs):
        if not instance.enabled:
            self.remove_object(instance,**kwargs)
        return instance.enabled

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读