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'
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!
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: ...
.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()
from django.db import connection
x = Artist.objects.get(name="Eminem")
print connection.queries[-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With