Django annotate with values: how to access values?
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
.
精彩评论