Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .query() function not working on Django ORM query?

Tags:

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 ?

like image 278
Moon Avatar asked Oct 30 '19 07:10

Moon


People also ask

Does Django ORM support subquery?

¶ Django allows using SQL subqueries.

How do I run a query in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

What are ORM queries in Django?

The object-relational mapper (ORM) in Django makes it easy for developers to be productive without prior working knowledge of databases and SQL. QuerySets represent a collection of objects from the database and can be constructed, filtered, sliced, or generally passed around without actually hitting the database.


1 Answers

.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).

like image 197
Willem Van Onsem Avatar answered Oct 12 '22 21:10

Willem Van Onsem