How does DRF by default render a manytomany field

28 views
Skip to first unread message

Jonathan Pham

unread,
Apr 12, 2018, 10:27:52 AM4/12/18
to Django REST framework
Posted SO question with code examples:

Trying to optimize my serializer.
DRF automatically renders a manytomany as a list of pks. Using the default with prefetch_related takes only 2 queries.
All I want to do is return an intersection of that list with the queried pks.

def get_failbin_regressions(self, obj):
        runids = self.context.get('runids')
        return obj.runs.values_list('id', flat=True)


However when accessing the many to many in a serializermethodfield causes a query for each row. Why is this? Is the prefetch lost in a serializermethodfield?
The end goal is to get a list with the same results as return obj.runs.values_list('id', flat=True).filter(id__in=runids)   without the extra queries.

Thanks!

Jonathan Pham

unread,
Apr 12, 2018, 12:54:50 PM4/12/18
to Django REST framework
Has been solved in SO
Reply all
Reply to author
Forward
0 new messages