[Answered ]-When QuerySet is evaluated when get_queryset is overridden

1👍

The problem is not the query, the problem is that the serializer needs to make additional queries to fetch the related objects. You should load these elements in the same query, with :

class SchoolsList(generics.ListAPIView):
    pagination_class = LargeResultsSetPagination
    serializer_class = SchoolGetSerializer

    def get_queryset(self):
        queryset = School.objects.all()

        user_id = self.request.query_params.get('user_id')
        if user_id is not None:
            queryset = queryset.filter(user_id=user_id)

        return queryset.select_related(
            'nearest_community', 'nearest_post_secundary', 'regional_district'
        ).order_by('id')

Since these serializer might query additional items, it is even possible that you should select additional fields, but these are not mentioned in your question.

0👍

Querysets are lazy. They are evaluated when you use them, not when you filter, order_by… so on. YourModel.objects is a Manager (see ModelManagers), with it you can do mass management easily (your queries). You need to check the number of connection to database, specially in loops. It’s very important (don’t make assumptions). Model.object.get_values() for get dictionaries can cause extra costs, for example, and you can fix it writing an specific Manager. If you need individual things, use model methods.

Did I answer your question?


This is wrong:

 return queryset.order_by('id')

You can’t do it. The query isn’t done yet.
At least, do it:

from django.http import JsonResponse
# code, code, code...

def any_view(request):
    # code, code, code...
    response = {'data': queryset.order_by('id').values()}
    return JsonResponse(response)

Leave a comment