On Nov 16, 2009, at 12:12 PM, despy wrote: > Hi, > > I'm trying to get my head around a complex aggregate query and I could > do with some help. Say I have the following models > > StockMarket > | > Stock > | > StockPrice > > If StockPrice has price and date fields, and one price entry for every > day for every stock how would I write a query to get the average price > for a given stockmarket for the last six months?
http://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-over-a-queryset prices = StockPrice.objects.filter(stock__market=SomeMarket, ... and so on avg = prices.aggregate(Avg('price')) Or something like that. Basically, you approach it from the other end. You want the market's aggregate, but the answer to that is an average of StockPrice objects, so you search for them with the conditions you want and then apply the aggregate operation to that. Adam Knight codepoetry - http://www.codepoetry.net/products/ -- 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=.