On Thu, Jan 14, 2010 at 7:56 AM, Bw. <b_w...@gmx.net> wrote: > Hi guys, > > I'm trying to realize a simple sql query in django for hours and I > don't get it. > > Description: > We have 'salesman' and 'disposals'. > 1 salesman has N disposals. > Now I need the average discount every salesman has given. > In mysql this query gives me the correct recordset: > > SELECT salesman.first_name, AVG(disposal.discount) > FROM disposal > LEFT JOIN salesman ON (salesman.id = disposal.salesman_id) > GROUP BY salesman_id > > In django i tried something like this: > sm = Disposal.objects.annotate(avg_discount=Avg('discount')).values > ('avg_discount','salesman__first_name')
In order to render this as a Django query, you need to stop thinking about the SQL, and start thinking about the problem in terms of the objects you want. If you ask for Disposal.objects.... then you're saying that you want Disposal objects to be returned. However, what you actually want is a list of Salesmen, each of which has a collection of Disposals. So - ask for Salesmen: Salesman.objects.annotate(avg_discount=Avg('disposal__discount') This will return a list of salesmen objects, each of which has been annotated with the average discount that they have offered on the Disposal objects that are related to them. Yours, Russ Magee %-)
-- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.