django prefetch_related for list of instances

Viewed 799

I was wondering if it is possible to prefetch related fields for already instantiated django objects.

for example let's say I have a group of instance of MyModel which I got from different sources (so I couldn't prefetch related the queryset at the first place) and I want to access related fields. I want to prefetch the fields for my list of objects in only 1 DB call.

Is there an elegant way to populate my instance prefetch cache? I was imagining something like


prefetch_related(list_of_instances, [field1, field2, field3])

1 Answers

By searching in the documentation, I found that django already has a function for that:

prefetch_related_objects(model_instances, *related_lookups) Prefetches the given lookups on an iterable of model instances. This is useful in code that receives a list of model instances as opposed to a QuerySet; for example, when fetching models from a cache or instantiating them manually.

Pass an iterable of model instances (must all be of the same class) and the lookups or Prefetch objects you want to prefetch for. For example:

from django.db.models import prefetch_related_objects
restaurants = fetch_top_restaurants_from_cache()  # A list of Restaurants
prefetch_related_objects(restaurants, 'pizzas__toppings')
Related