使用update_index --remove从Haystack/Xapian索引中删除

Dar*_*ryl 3 django django-haystack

我正在尝试让./manage.py update_index --remove管理命令从搜索索引中删除结果.

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

enabled = models.BooleanField()
Run Code Online (Sandbox Code Playgroud)

领域是 False

我该怎么办?我还需要准备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)
Run Code Online (Sandbox Code Playgroud)

谢谢.

Sha*_*hin 7

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

{# in search/indexes/yourapp/article_text.txt #}
{% if object.enabled %}
    {# ... whatever you have now #}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

当您运行时./manage.py update_index,文章enabled=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
Run Code Online (Sandbox Code Playgroud)