5

As I already know that using .query.__str__() , we can get sql equivalent query from Django ORM query.

e.g : Employees.objects.filter(id = int(id)).query.__str__()

Above code working well & I am able to get sql equivalent query but when I am using same on below query I am getting error like below.

Employees.objects.filter(id = int(id)).first().query.__str__()
AttributeError: 'Employees' object has no attribute 'query'

Why now I am getting error, any suggestions ?

1 Answer 1

4

.first() [Django-doc] does not return a QuerySet, it returns a model object. The query is evaluated eagerly.

You can inspect the last query that Django made with:

from django.db import connection
print(connection.queries[-1:])

That being said, in essence a some_queryset.first() is often the same query as some_queryset, except that it will limit the queryset.

Note: Please do not use .__str__, you can use str(my_queryset.query), or just print(my_queryset.query).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! Above explanation clear my doubts & solved my problem !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.