Reputation: 341
I have a model Product with a lot of fields (~50). I have a filter like :
sale = Product.objects.filter(id=2)
But this give me all 50 fields for id = 2, so I tried to add only to reduce the queryset size since I only need 2 fields:
sale = Product.objects.filter(id=2).only("Origin","Price")
Now I want to access to the price with sale.Price but I have the error
'QuerySet' object has no attribute 'Price'
Upvotes: 1
Views: 492
Reputation: 476614
You use .filter(…)
[Django-doc] this does not return a single Product
object, but a QuerySet
of Product
s. You thus can not use sale.Price
, since it is not a single Product
, but a collection of Product
s.
You should use .get(…)
[Django-doc] to retrieve a Product
object. Since .get(…)
will immediately query, you thus need to place the .only(…)
clause in front:
sale = Product.objects.only('Origin', 'Price').get(id=2)
Upvotes: 2