Dean Christian Armada
Dean Christian Armada

Reputation: 7364

What does .only django queryset really do?

I heard in the Django documentation it optimizes so I did a little bit of experimentation. So I did this:

>>> x = Artist.objects.only('id').filter()
>>> print x.query
SELECT "store_artist"."id" FROM "store_artist"

>>> y = Artist.objects.filter()
>>> print y.query
SELECT "store_artist"."id", "store_artist"."name", "store_artist"."birth_date" FROM "store_artist"

I can see that the query changed however I did a further test:

>>> for _x in x:
    ... _x.name
    ... 
    u'Beyone'
    u'Beyoneeee'
    u'Beyone231231'
    u'Beyone2222'
    u'No Album'

>>> for _y in y: 
    ...  _y.name
    ...
    u'Beyone'
    u'Beyoneeee'
    u'Beyone231231'
    u'Beyone2222'
    u'No Album'

So if you've noticed it just has the same result. How did that happen? I thought that in the y variable I just fetched the id so the name should not appear or be invalid

Here is my model by the way:

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

Upvotes: 3

Views: 992

Answers (2)

d-ashu
d-ashu

Reputation: 57

The .only method returns you a queryset which is not appendable, if you want a new queryset you have to make an another query to get that. This method is useful when you have a very large dataset and you want a only field for all your processing in the business logic. In your case i will suggest to use defer() method. You can make multiple calls to defer(). Each call adds new fields to the deferred set. so now, its upto you among the set which value you want to use from it, and the main thing you havnt require to make a call again to database for fetching values which helps you in optimization and performance.

Upvotes: 2

Sayse
Sayse

Reputation: 43300

It does only query the fields you give it, but then it still returns instances of that model. So when you ask for a different field, you would have made a second query to get the name

Upvotes: 3

Related Questions