Django 从haystack索引中删除对象
我使用django删除记录:Django 从haystack索引中删除对象,django,indexing,django-haystack,Django,Indexing,Django Haystack,我使用django删除记录: r = model.objects.get(id=1) r.delete() 现在,我想从索引中删除记录,而不重新编制索引。怎么做 我无法让remove_对象工作,并且级别太高。我不能只运行“python manage.py update_index--remove”,因为这也会重新索引所有内容 Ha,答案很简单,但很简单。基本上,下面的代码是有效的,因为如果计时正确(在最后一个小时内数据库中没有条目),它只会删除已删除记录的索引条目。瞧 python m
r = model.objects.get(id=1)
r.delete()
现在,我想从索引中删除记录,而不重新编制索引。怎么做
我无法让remove_对象工作,并且级别太高。我不能只运行“python manage.py update_index--remove”,因为这也会重新索引所有内容 Ha,答案很简单,但很简单。基本上,下面的代码是有效的,因为如果计时正确(在最后一个小时内数据库中没有条目),它只会删除已删除记录的索引条目。瞧
python manage.py update_index --remove --age=1
实际上,一个更简单的解决方案是使用SignalProcessor(),当您从orm中删除文档时,连接到post_delete将自动删除该文档。删除单个对象有两个选项
- 第一种方法:
类SearchIndex
您可以提供实例对象以及应该使用的连接
SearchIndex.remove_对象(self,instance,using=None,**kwargs)
从索引中删除对象。附加到类的post delete挂钩
SearchIndex.update\u对象(self,instance,using=None,**kwargs)
更新单个对象的索引。附加到类的post save挂钩
如果提供了使用的,它将指定应使用的连接。>默认情况下,路由器决定应该使用哪个后端
例如:
from myapp.search_indexes import MyIndex
# Get the object you want to delete or update
instance = YourModel.objects.get(id=id)
# settings.HAYSTACK_CONNECTIONS / name of your index
using = "myindex_name"
# Remove object
MyIndex().remove_object(instance, using)
# Update object
MyIndex().update_object(instance, using)
- 第二种方法:
可以通过删除单个对象
以下是一些例子:
from haystack import connections as haystack_connections
# Get the object you want to delete or update
instance = YourModel.objects.get(id=id)
# Get all Names/keys of your indexes / settings.HAYSTACK_CONNECTIONS
backend_names = haystack_connections.connections_info.keys()
# Get key of connection for your object
using = backend_names[0]
# Get the backend
backend = haystack_connections[using].get_backend()
# To remove object
backend.remove(instance)
实际上,它将重新索引所有内容: