Accessing hidden prefetched fields in Django

Rudi Theunissen Blocked Unblock Follow Following Nov 30, 2015

Note: This relates to Django 1.7

I recently came across an interesting case where a relatively simple JSON endpoint was making over 100 queries, which was about 10x more than expected. The obvious solution was to prefetch the related fields, so that the serializer doesn’t have to fetch each field individually. However, this did not have a significant effect; serializing 10 models still created ~100 queries.

What happens here is that the RelatedManager (related_set) is not aware of the fields we prefetched earlier, which is why it had no effect. We need to find a way to somehow use the prefetched related fields in the serializer.

We are passing each instance to the serializer separately, which is okay. The problem to solve is how we can access the prefetched related fields. We can do that using an internal property called _prefetched_objects_cache: