2

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.

4

3 に答える 3

5

item = AModel.objects.get(id = 100)等しい

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

したがって、実行されるクエリは次のようになります。AModel.objects.filter(id = 100)

また、の最新アイテムをチェックすることができますconnection.queries

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

そして、FoxMaSkが言ったdjango-debug-toolbarように、それをブラウザにインストールして楽しんでください。

于 2012-08-29T14:47:00.883 に答える
3

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, e.g.

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.

于 2012-08-29T14:49:31.647 に答える
2

if it's just for debugging purpose you can use "the django debug bar" which can be installed by

pip install django-debug-toolbar
于 2012-08-29T14:39:02.113 に答える