[Fixed]-Use prefetch_related in django_simple_history


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)

Leave a comment