Search code examples
djangopostgresqldjango-modelsdjango-rest-frameworkdjango-views

Hit DB only once while filtering a queryset in Django-rest-framework


I am filtering a model under some conditions say, qs = Model.objects.filter(category=value). I am send this queryset as a response using ListModelMixin.

class ModelViewset(ListModelmixin):
    def get_queryset(self):
        return Model.objects.filter(category=value)

The select statement was running n times for n items which seems reduntant, Somehow I want to hit db only once and use them as Response.

I tried list, but it has too much overhead and has slowed down the performance. Is there any way to acheive this by not using list, bool or remaining things as they will also execute each items which results in n queries for n items in Model.

Update:

Thank you Willem for guiding to the solution.


Solution

  • There are some foreign keys that I have not prefetched (prefetch_related or select_related) which is causing N+1 problem.

    add .select_related(foreign_fields) or .prefetch_related(m2m_fields) clause to query which will solve N+1 problem.

    In my case:

    return Model.objects.filter(category=value).select_related(*foreign_key_fields)

    solved my problem.

    reference: N+1 Queries in Django