Django ORM "get" translation to SQL

For a Queryset in Django, we can call its method .query to get the raw sql.

for example,

queryset = AModel.objects.all()
print queryset.query

the output could be: SELECT "id", ... FROM "amodel"

But for retrieving a object by "get", say,

item = AModel.objects.get(id = 100)

how to get the equivalent raw sql? Notice: the item might be None.


The item = AModel.objects.get(id = 100) equals to

items = AModel.objects.filter(id = 100)
if len(items) == 1:
    return items[0]
else:
    raise exception

Thus the executed query equals to AModel.objects.filter(id = 100)

Also, you could check the latest item of connection.queries

from django.db import connection # use connections for non-default dbs
print connection.queries[-1]

And, as FoxMaSk said, install django-debug-toolbar and enjoy it in your browser.


It's the same SQL, just with a WHERE id=100 clause tacked to the end.

However, FWIW, If a filter is specific enough to only return one result, it's the same SQL as get would produce, the only difference is on the Python side at that point, eg

AModel.objects.get(id=100)

is the same as:

AModel.objects.filter(id=100).get()

So, you can simply query AModel.objects.filter(id=100) and then use queryset.query with that.


如果仅仅是为了调试目的,你可以使用可以通过安装的“django调试栏”

pip install django-debug-toolbar
链接地址: http://www.djcxy.com/p/38704.html

上一篇: .update(...)带有额外的(...)和F(...)

下一篇: Django ORM“获得”到SQL的翻译