在django_simple_history中使用prefetch_lated

问题描述 投票:0回答:2

我有一个预订模型,里面有历史。像这样,我使用 django_simple_history

class Booking(CreatedAtAbstractBase):
    history = HistoricalRecords()

我使用管理命令来执行任务。因为我想在预订时预取历史记录

booking_p_history = Booking.history.filter(s_id=6).order_by(
                'updated_at').first()    
booking_obj_list = Booking.objects.select_related(...) \
                    .prefetch_related(
                    Prefetch('booking_history', queryset=booking_p_history, to_attr='driver_pickup_history')
                    ,'booking_history') \
                    .filter(...)

如何在预取中使用简单的历史记录?

python django prefetch django-simple-history
2个回答
8
投票

最终答案基本上是“你不能”。这是有道理的。根据我打开的

由于历史记录是一个管理器而不是一个外键字段,因此 objs = MyModel.objects.all().prefetch_lated('history') 将不起作用。目前,我们没有任何定义的方法来实现您的功能,我也没有立即想到任何东西,因为我不知道 django 如何实现 prefetch_lated 的来龙去脉。

但是,您可以直接查询历史表,缓存结果,然后使用评估的查询集进行检查。有关缓存和查询集的更多信息,请查看此处。所以我想你可以保存历史记录并像这样查询它:

history_objs = MyModel.history.all()
objs = MyModel.objects.all()

history_for_first_object = filter(lambda x: x.id == objs.first().id, history_objs)

0
投票

最近

django-simple-history
使得预取对象的历史记录成为可能。 例如:

class Book(models.Model):
    name = models.CharField(max_length=200)
    history = HistoricalRecords(related_name='book_history')

这样您就可以过滤历史记录和 prefetch_lated 了:

Book.objects.filter(book_history__history_user=1)
Book.objects.prefetch_related('book_history')

注: 由于

related_name='book_history'
创建非空外键字段,因此您不能简单地使用现有历史表进行迁移。就我而言,删除它并创建一个新表是可以接受的,但最好在设计模型时提供
related_name

文档

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.