我有一个模型,它有一个 bool 字段,用于说明模型对象是否处于事件状态。我基本上希望 Haystack 忽略任何具有 active=False 的对象。这适用于完整的重建索引,使用:
def index_queryset(self, using=None):
return ExampleModel.objects.filter(active=True)
然而,当一个对象被更新并且索引被实时更新并且没有完全重新索引时,例如当将一个对象更改为非事件状态时,以下内容不起作用并且似乎没有被调用:
def should_update(self, instance):
if instance.active:
return True
self.remove_object(instance)
return False
我希望对象在被标记为非事件时从索引中删除,但是在将对象更新为非事件时,它仍保留在影响方面计数等的索引中。我使用 manage.py update_index 进行了检查,而 should_update 代码没有好像在跑?
有关信息,我正在使用 haystack dev 和 elasticsearch 最新稳定版。
有什么想法吗?
请您参考如下方法:
查看源代码,should_update()默认情况下返回 True,这意味着重新索引。此外,remove_object()附加到类的删除后 Hook ,这可能是它没有被调用的原因,因为您没有删除记录。
你应该能够通过像这样稍微改变你的代码来触发索引删除:
def should_update(self, instance, **kwargs):
if instance.active:
return True
else:
self.remove_object(instance, **kwargs)
return False
或相反:
def should_update(self, instance, **kwargs):
if not instance.active:
self.remove_object(instance, **kwargs)
return instance.active
另一种选择是创建一个 CRON 脚本来执行以下操作:
import haystack
from yourapp.models import ExampleModel
for obj in ExampleModel.objects.filter(active=False):
haystack.site.remove_object(obj)
这也可以被 post_save 使用Django 中的信号。
细则:我未测试此代码的任何。它是理论上的,基于问题中提供的信息。
