[Django]-Django REST Framework: Setting up prefetching for nested serializers

21👍

prefetch_related() supports prefetching inner relations by using double underscore syntax:

queryset = queryset.prefetch_related('reading_group', 'reading_group__users', 'reading_group__owner') 

I don’t think Django REST provides any elegant solutions out of the box for fetching all necessary fields automatically.

👤serg

8👍

An alternative to prefetching all nested relationships manually, there is also a package called django-auto-prefetching which will automatically traverse related fields on your model and serializer to find all the models which need to be mentioned in prefetch_related and select_related calls. All you need to do is add in the AutoPrefetchViewSetMixin to your ViewSets:

from django_auto_prefetching import AutoPrefetchViewSetMixin

class ReadingGroupViewset(AutoPrefetchViewSetMixin, views.ModelViewset):

  def get_queryset(self):
    qs = ReadingGroup.objects.all()
    return qs

class UserBookStatsViewset(AutoPrefetchViewSetMixin, views.ModelViewset):

  def get_queryset(self):
    qs = UserBookStats.objects.all()
    return qs

Any extra prefetches with more complex Prefetch objects can be added in the get_queryset method on the ViewSet.

👤davish

Leave a comment