Django: How To Prefetch Related For A Model Instance. Perhaps By Wrapping In A Queryset?
I use Django rest framework and I have decent nesting in my model relations. I'm working on optimizing my queries. Many of my functions consume or manipulate a single instance of m
Solution 1:
I haven't yet used this myself, but I believe that it is the prefetch_related_objects()
function that you are looking for, introduced in Django 1.10
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')
Since it takes an iterable, you can wrap your instance in a list:
prefetch_related_objects([profile], "relevant_attribute_1", "relevant_attribute_2")
Post a Comment for "Django: How To Prefetch Related For A Model Instance. Perhaps By Wrapping In A Queryset?"