Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 653
RoyalBosS Avatar asked Oct 23 '25 03:10

RoyalBosS


1 Answers

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.

like image 65
Alessandro Salvetti Avatar answered Oct 25 '25 18:10

Alessandro Salvetti