Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use prefetch_related in django_simple_history

I have a model Booking which has a history in it. like this and I use django_simple_history

class Booking(CreatedAtAbstractBase):
    history = HistoricalRecords()

And I use a management command to do tasks. In that I wanted to Prefetch history when taking a booking

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(...)

How to use simple history inside prefetch?

like image 346
Deepakraj Murugesan Avatar asked Aug 16 '17 12:08

Deepakraj Murugesan


1 Answers

Ends up the answer is basically "you can't". And it makes sense. As per the ticket I opened:

Since history is a manager rather than a ForeignKey field, objs = MyModel.objects.all().prefetch_related('history') won't work. Right now, we don't have any defined way of implementing your feature, and nothing immediately comes to mind for me as I don't know the ins and outs of how django implements prefetch_related.

You could, however, query the historical table directly, cache the results, and then use the evaluated queryset for your checks. For more on caching and querysets, look here. So I'm thinking you could hold the history and query it like this:

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

history_for_first_object = filter(lambda x: x.id == objs.first().id, history_objs)
like image 101
Jamie Counsell Avatar answered Sep 22 '22 05:09

Jamie Counsell