Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the query of .get queryset in django

Tags:

python

django

How can I know the query when doing a .get queryset in django

I have this model:

class Artist(EsIndexable, models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()

And I did this in the shell:

x = Artist.objects.get(name="Eminem")
print x.query

Then I got the error:

AttributeError: 'Artist' object has no attribute 'query'
like image 814
Dean Christian Armada Avatar asked Sep 08 '16 08:09

Dean Christian Armada


People also ask

How do I get SQL 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!

How do I get QuerySet in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...


2 Answers

.get returns an instance, not a queryset.

To see the query that is done, do the same thing but with .filter, which does return a queryset:

queryset = Artist.objects.filter(name="Eminem")
print queryset.query
x = queryset.get()
like image 119
RemcoGerlich Avatar answered Oct 10 '22 16:10

RemcoGerlich


from django.db import connection

x = Artist.objects.get(name="Eminem")
print connection.queries[-1]
like image 23
Sergey Gornostaev Avatar answered Oct 10 '22 16:10

Sergey Gornostaev