How to get the SQL from a Django QuerySet

0 votes
I'm trying to debug , but I'm not sure what queries are going to the database. How do I get the SQL that Django will use on the database from a QuerySet object?
Jun 23, 2020 in Python by kartik
• 37,510 points
448 views

1 answer to this question.

0 votes

Hello @kartik,

Try this in your queryset:

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

Hope it helps!

Thank You!!

answered Jun 23, 2020 by Niroj
• 82,720 points

Related Questions In Python

0 votes
3 answers

How to get the return value from a thread using python?

FWIW, the multiprocessing module has a nice interface for ...READ MORE

answered Dec 15, 2020 in Python by Roshni
• 10,440 points
59,927 views
0 votes
1 answer

How to choose the value and label from Django ModelChoiceField queryset?

Hello @kartik, In your Person model add: def __unicode__(self): ...READ MORE

answered Jul 29, 2020 in Python by Niroj
• 82,720 points
2,439 views
0 votes
1 answer

How to get the current URL within a Django template?

Hello @kartik, You can fetch the URL in ...READ MORE

answered Aug 6, 2020 in Python by Niroj
• 82,720 points
2,496 views
0 votes
1 answer

How to clear a database from the CLI with manage.py in Django?

Hello @kartik, To drop the database and run syncdb again. ...READ MORE

answered Aug 7, 2020 in Python by Niroj
• 82,720 points
565 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,033 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,556 views
0 votes
1 answer

How do I add a link from the Django admin page of one object to the admin page of a related object?

Hello @kartik, Set show_change_link to True (False by default) in your inline ...READ MORE

answered Jun 12, 2020 in Python by Niroj
• 82,720 points
2,728 views
0 votes
1 answer

How to execute a Python script from the Django shell?

Hello @kartik, The << part is wrong, use < instead: $ ./manage.py shell ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,720 points
4,492 views