[Django]-Get all values from Django QuerySet plus additional fields from a related model

0👍

You can use prefetch_related for this. See docs:

You want to use performance optimization techniques like deferred
fields:

queryset = Pizza.objects.only(‘name’)

restaurants = Restaurant.objects.prefetch_related(Prefetch(‘best_pizza’, queryset=queryset))

In your case you can do something like this:

from django.db.models import Prefetch

queryset = A.objects.only('text')
b_list = B.objects.prefetch_related(Prefetch('a', queryset=queryset))

0👍

Maybe something like this would work in your case?

B.objects.select_related('a').defer('a__field_to_lazy_load');

This will load all fields from both models except the ones you specify in defer(), where you can use the usual Django double underscore convention to traverse the relationship.

The fields you specify in defer() won’t be loaded from the db but they will be if you try to access them later on (e.g. in a template).

Leave a comment