如何在删除,添加和更新模型实例时仅将algolia与数据库同步

时间:2018-01-22 06:33:09

标签: django algolia

根据algoliasearch-django文档:

  

AUTO_INDEXING:自动将模型与Algolia同步(默认为True)。

根据我的理解,如果我将AUTO_INDEXING设置为True,每当我更新模型实例或更新模型(例如添加新字段)时,它都会将Algolia与我自己的数据库(或模型)同步。但是,我想要做的是按需同步Algolia ,例如,只有在更改,添加或删除模型实例时才同步它们。有没有办法实现这个?感谢。

1 个答案:

答案 0 :(得分:6)

启用AUTO_INDEXING时,告诉Algolia的Django集成连接到Django的pre-savepost-save信号。这些提供了一个机会,可以在您的某个实例更新时做出反应,Algolia在此处使用它来同步索引中的这些更改。

As you can see in 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,
    )

所以Algolia的AUTO_INDEXING只能依赖这些trigger to update your records

    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)

考虑到这一点,AUTO_INDEXING无法猜测您是否因为创建了新实例或而调用了instance.save() ,因为您的模型已更新,更新所有现有实例AUTO_INDEXING旨在触发索引每次更新您的实例(通过添加新字段,更改当前字段,添加实例或删除实例),以确保您的Algolia索引始终如一与您的Django数据库同步。

如果您想实现更加自定义的与Algolia同步的处理,您可以:

  • 禁用AUTO_INDEXING
  • 在使用Algolia注册模型后的apps.py中,连接到相应的信号:

        algoliasearch.register(Contact, ContactIndex)
        post_save.connect(my_post_save_receiver, ContactIndex)
        pre_delete.connect(my_pre_delete_receiver, ContactIndex)
    
  • 在您的my_post_save_receiver / my_pre_save_receiver方法中,处理Signal参数以决定是否要调用index.save_record(instance)

查看Signals documentationSignals guide。请注意 duplicate signals部分。