MichaelS
MichaelS

Reputation: 341

DJANGO - Reduce amount of field in queryset

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You use .filter(…) [Django-doc] this does not return a single Product object, but a QuerySet of Products. You thus can not use sale.Price, since it is not a single Product, but a collection of Products.

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

Related Questions