如何更新由多个数据模型组成的Algolia索引

时间:2018-09-25 15:05:37

标签: python algolia

我们有一个模型订单。这参考了不同的表实现。我需要从两个表中获取详细信息以进行索引。我通过重写get_raw_record()函数实现了索引的get部分。但我无法弄清楚更新将如何工作。也就是说,无论执行情况有何变化,订单索引都应更新。

# from index.py file 
@register(Order)
class OrderIndex(AlgoliaIndex):
    custom_objectID = 'id'
    index_name = 'orders'
    fields = (
        'name', 'created_at', 'total_price', 'fulfillment_status', 'email', 'tags', 'item_names')

    def get_raw_record(self, instance, update_fields=None):
        algolia_dict = instance.algolia_fields
        res_dict = super(OrderIndex, self).get_raw_record(instance, update_fields)
        return merge_two_dicts(res_dict, algolia_dict)

# Order and Fulfillment models:

class Order(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    oid = models.BigIntegerField()
    email = models.CharField(max_length=100)
    closed_at = models.DateTimeField(blank=True, null=True)
    created_at = models.DateTimeField()
    updated_at = models.DateTimeField()
    no = models.CharField(max_length=100)
    test = models.BooleanField(default=False)
    total_price = models.FloatField(blank=True, null=True)
    currency = models.CharField(max_length=10, blank=True, null=True)
    name = models.CharField(max_length=50)
    fulfillment_status = models.CharField(max_length=20, blank=True, null=True)
    tags = models.CharField(max_length=200, blank=True, null=True)
    shipping_address = JSONField(default=dict)
    customer_info = JSONField()

    @property
    def algolia_fields(self):
        fulfillmemt_ids = [item.id for item in self.order_fulfillments.all()]
        return {'customer_info': {
            'first_name': self.customer.first_name,
            'last_name': self.customer.last_name,
            'email': self.customer.email,
            'phone': self.customer.phone

        },
            'created_date': arrow.get(self.created).to('UTC').datetime.strftime('%Y%m%d'),
            'viewable': [self.customer.id, self.retailer.id],
            'fulfillmemt_ids': fulfillmemt_ids
        }


    class Meta:
        db_table = 'order'


class Fulfillment(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_fulfillments')

1 个答案:

答案 0 :(得分:0)

很高兴我们可以在Discourse forum上回答您。在此处重新发布响应以使社区受益。

  

实际上,您需要在Algolia的Order下嵌套Fultillments,   并且只有索引。

     

我在线检查过,看来最好的解决方案是   实现实现的自定义保存方法,该方法调用Order.save。   您还可以连接到订单的post_save或pre_save信号。   这是基于我在这里阅读的内容,对我来说很有意义,但是我有   坦白,我不是Django专家

     

Django trigger parent model save when editing inline in admin