[Answered ]-How do I optimize the SQL for this Django view?

2👍

You should use prefetch_related which is used to make efficient queries concerning reverse foreign keys or many-to-many relationships:

From the docs:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single
batch, related objects for each of the specified lookups.

def get_queryset(self,*args,**kwargs):
     return Submissions.objects.all().prefetch_related('stats_set')

It will require an additional query, but the idea is that it will get all of the related information at once, instead of once per Submissions object.

On a side note it’s recommended to use the singular of a noun for the model class name: Submission instead of Submissions.

Leave a comment