开发者

Django annotate with values: how to access values?

开发者 https://www.devze.com 2022-12-16 12:57 出处:网络
I have a model with \"disposals\" and a model with \"salesman\". I want to get the average discount of everye salesman.

I have a model with "disposals" and a model with "salesman". I want to get the average discount of everye salesman. Here's what I'm trying:

sm = Disposal.objects.annotate(average_discount=Avg('discount')).values('average_discount','sm__fname','sm__lname').order_by('-discount')
    for s in sm:
         data[0] = data[0]+s.sm__fname+','+s.sm__lname+','+str(s.average_discount)
开发者_如何转开发

Now I get this error:

Disposal object has no attribute sm__fname

The query runs fine when I execute it in the django shell - but how can I access the values? Thank you very much!


Firstly, as the documentation says, using values gives you a list of dictionaries, not model objects. So each s doesn't have an attribute sm_whatever, it has a dictionary key. So try this:

s['sm__lname']

However, I must say that I don't see the need to use values here at all. You would be better off just getting the actual objects:

sm = Disposal.objects.annotate(average_discount=Avg('discount')).order_by('-discount')

and then accessing the relevant related objects normally: s.fname.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号