在django_simple_history中使用prefetch_related

Dee*_*san 13 python django prefetch django-simple-history

我有一个模型预订,其中有一个历史.像这样,我使用django_simple_history

class Booking(CreatedAtAbstractBase):
    history = HistoricalRecords()
Run Code Online (Sandbox Code Playgroud)

我使用管理命令来完成任务.我想在预订时预取历史记录

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(...)
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*ell 5

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

由于 history 是管理器而不是 ForeignKey 字段,因此 objs = MyModel.objects.all().prefetch_related('history') 将不起作用。现在,我们没有任何定义的方式来实现您的功能,我没有立即想到任何东西,因为我不知道 django 如何实现 prefetch_related 的来龙去脉。

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

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

history_for_first_object = filter(lambda x: x.id == objs.first().id, history_objs)
Run Code Online (Sandbox Code Playgroud)