Search code examples
sqldjangodjango-modelsdjango-querysetdjango-debug-toolbar

Get number of sql queries in django rest framework


Suppose

@login_required()
def GetFollowers(request, id):
    obj = Follow.objects.filter(following_id=id)
    serializer = SearchSerializer(obj, many=True)
    result = JsonResponse(serializer.data, safe=False)
    return result

I am using django rest framework. When I hit an api endpoint suppose (localhost:8000/api/v1/myfollowers) i get a json result which is ok but not getting django-debug-toolbar. When i raise(Http404) instead of returning JSON result, django debug toolbar is visible.

How do i fix this? A way i got to know was printing queries but i cant use that as i will have to add same lines to every function.

Thanks in Advance!


Solution

  • You can use the connection.queries variable like this:

    # from django.db import connection
    
    @login_required()
    def GetFollowers(request, id):
        print('number of DB hits (queries) at the beginning', len(connection.queries))
        obj = Follow.objects.filter(following_id=id)
        serializer = SearchSerializer(obj, many=True)
        result = JsonResponse(serializer.data, safe=False)
        print('number of DB hits (queries) at the end', len(connection.queries))
        return result
    
    

    This solution is applicable because you are explicitly doing the queries. Instead, if you start using DjangoRestFramework with serializers and let it doing everything behind the scene, you'll need to find a different approach.