Skip to main content
 首页 » 编程设计

python之如何更新 django-haystack 的单个记录

2025年02月15日36java哥

我是一个 haystack 初学者,我正在尝试弄清楚如何更新文档。

我有以下 SearchIndex:

class ProductIndex(indexes.SearchIndex, indexes.Indexable): 
    text = indexes.CharField(document=True) # contains keywords associated with the product 
    name= indexes.CharField(model_attr='name') 
 
    def get_model(self): 
        return Product 
 
    def prepare_text(self, obj): 
        return [tag.keyword for tag in obj.productkeywords_set.all()] 

我想在用户添加新产品关键字时更新 text 字段。我有超过 80k 条记录,所以当我使用 python manage.py update_index 时需要很长时间。有没有办法只更新一个文档?

请您参考如下方法:

您可以使用信号处理器 https://django-haystack.readthedocs.io/en/master/signal_processors.html#realtime-realtimesignalprocessor

The other included SignalProcessor is the haystack.signals.RealtimeSignalProcessor class. It is an extremely thin extension of the BaseSignalProcessor class, differing only in that in implements the setup/teardown methods, tying ANY Model save/delete to the signal processor.

If the model has an associated SearchIndex, the RealtimeSignalProcessor will then trigger an update/delete of that model instance within the search index proper.

Configuration looks like:

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

This causes all SearchIndex classes to work in a realtime fashion.

通过启用它,您的索引将在模型上保存/删除时自动更新