646👍
You print the queryset’s query
attribute.
>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
73👍
Easy:
print(my_queryset.query)
For example:
from django.contrib.auth.models import User
print(User.objects.filter(last_name__icontains = 'ax').query)
It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:
from django.db import connections
connections['default'].queries
The django debug toolbar project uses this to present the queries on a page in a neat manner.
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-Django-reversion and related model
- [Django]-Django – getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
68👍
The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90>
.
The following returned the query:
>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()
- [Django]-OneToOneField() vs ForeignKey() in Django
- [Django]-Django: How to get related objects of a queryset?
- [Django]-How to resize the new uploaded images using PIL before saving?
12👍
This middleware will output every SQL query to your console, with color highlighting and execution time, it’s been invaluable for me in optimizing some tricky requests
- [Django]-Django url tag multiple parameters
- [Django]-Django logging of custom management commands
- [Django]-How does the get_or_create function in Django return two values?
12👍
As an alternative to the other answers, django-devserver outputs SQL to the console.
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-Disabled field is not passed through – workaround needed
- [Django]-Many-To-Many Fields View on Django Admin