简体   繁体   English

如何在Django Rest API的基于类的视图中打印原始查询

[英]How to print raw query in class based view in django rest api

I am working on django rest api and using class based views like : 我正在使用django rest api并使用基于类的视图,例如:

class UserViewSet(viewsets.ModelViewSet):

   queryset = Users.objects.filter(user_type_id=3)

   def get_queryset(self):
       queryset = self.queryset

       city = self.request.QUERY_PARAMS.get('city', '') 
       if city!="":
            queryset = queryset.filter(work_address__city__icontains=city).distinct()

       return queryset

and In url.py file : 并在url.py文件中:

router.register(r'api/users', views.UsersViewSet)

So I want to print raw mysql query in UserViewSet. 所以我想在UserViewSet中打印原始的mysql查询。 So that I can see the query. 这样我就可以看到查询。 Is it there any method to see the raw query when we would make call "api/users". 当我们调用“ api / users”时,是否有任何方法可以查看原始查询。

You can either install the django debug toolbar: 您可以安装django调试工具栏:

https://pypi.python.org/pypi/django-debug-toolbar https://pypi.python.org/pypi/django-debug-toolbar

or use: 或使用:

# at the top of the file
from django.db import connection

# and put this before return queryset
connection.queries

to output the SQL queries in the log. 在日志中输出SQL查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM