根据algoliasearch-django文档:
AUTO_INDEXING:自动将模型与Algolia同步(默认为True).
根据我的理解,如果我设置AUTO_INDEXING为True,每当我更新模型实例或更新模型(例如添加新字段)时,它都会将Algolia与我自己的数据库(或模型)同步.但是,我想要做的是按需同步Algolia ,例如,只有在更改,添加或删除模型实例时才同步它们.有没有办法实现这个?谢谢.
启用时AUTO_INDEXING,您可以告诉Algolia的Django集成连接到Django pre-save和post-saveSignals.当您的某个实例更新时,这些机会可以做出反应,Algolia在此处使用它来同步索引中的这些更改.
如您所见django/db/models/base.py,这些是调用模型save()方法时发送的唯一信号:
if not meta.auto_created:
pre_save.send(
sender=origin, instance=self, raw=raw, using=using,
update_fields=update_fields,
)
#...
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin, instance=self, created=(not updated),
update_fields=update_fields, raw=raw, using=using,
)
Run Code Online (Sandbox Code Playgroud)
所以Algolia AUTO_INDEXING只能依靠这些作为更新记录的触发器:
if (isinstance(auto_indexing, bool) and
auto_indexing) or self.__auto_indexing:
# Connect to the signalling framework.
post_save.connect(self.__post_save_receiver, model)
pre_delete.connect(self.__pre_delete_receiver, model)
def __post_save_receiver(self, instance, **kwargs):
"""Signal handler for when a registered model has been saved."""
logger.debug('RECEIVE post_save FOR %s', instance.__class__)
self.save_record(instance, **kwargs)
def __pre_delete_receiver(self, instance, **kwargs):
"""Signal handler for when a registered model has been deleted."""
logger.debug('RECEIVE pre_delete FOR %s', instance.__class__)
self.delete_record(instance)
Run Code Online (Sandbox Code Playgroud)
考虑到这一点,没有办法AUTO_INDEXING猜测你是否instance.save() 因为你创建了一个新实例而调用了,或者因为你的模型已经更新,所以更新了所有现有的实例.AUTO_INDEXING用于在每次更新实例时触发索引(通过添加新字段,更改当前字段,添加实例或删除实例),以确保您的Algolia索引始终与Django数据库同步.
如果您想实现更加自定义的与Algolia同步的处理,您可以:
AUTO_INDEXING在您apps.py使用Algolia注册模型后,请连接到相应的信号:
algoliasearch.register(Contact, ContactIndex)
post_save.connect(my_post_save_receiver, ContactIndex)
pre_delete.connect(my_pre_delete_receiver, ContactIndex)
Run Code Online (Sandbox Code Playgroud)在您的my_post_save_receiver/ my_pre_save_receiver方法中,处理Signal参数以决定是否要调用index.save_record(instance).
查看Signals文档和Signals指南.请注意重复信号部分.
| 归档时间: |
|
| 查看次数: |
257 次 |
| 最近记录: |