Re: Optimizing DB query involving annotate and aggregate

2014-02-11 Thread ST
Managed it in the end, so for reference here is what I ended up with: def total_credit_debt(self): transaction_totals = Transaction.objects.filter(member__isnull=False).values('member').annotate(total=Sum('amount')).order_by() creditors = transaction_totals.filter(total__gt=0)

Re: Optimizing DB query involving annotate and aggregate

2014-02-06 Thread Arnold Krille
On Wed, 5 Feb 2014 10:11:29 -0800 (PST) ST wrote: > Hi, > > I'm trying to optimize the run-time of getting total credit and debt > values out of our database. Ideally I'd like to formulate it as a > Django query. This is the raw SQL query I have, which produces the > right answer and is very fast

Re: Optimizing DB query involving annotate and aggregate

2014-02-06 Thread Erik Cederstrand
Den 06/02/2014 kl. 12.34 skrev ST : > This didn't work - it produced a "SELECT FROM" query, which obviously didn't > work - tried adding 'amount' to the values_list, but that didn't help either. > Eventually got it to work by using .only('member', 'amount') instead, and it > *was* fast, but it

Re: Optimizing DB query involving annotate and aggregate

2014-02-06 Thread ST
On Wednesday, February 5, 2014 8:01:53 PM UTC, Anssi Kääriäinen wrote: > > Something like this might work: > > Transaction.objects.values_list('member_id').annotate(total=Sum('amount')).filter(total__gt=0).aggregate(Sum('total')) > This didn't work - it produced a "SELECT FROM" query, which

Re: Optimizing DB query involving annotate and aggregate

2014-02-05 Thread Anssi Kääriäinen
Something like this might work: Transaction.objects.values_list('member_id').annotate(total=Sum('amount')).filter(total__gt=0).aggregate(Sum('total')) That is, don't start from Member, Django isn't smart enough to get rid of the non-necessary joins. Instead go directly for the query you wrot

Optimizing DB query involving annotate and aggregate

2014-02-05 Thread ST
Hi, I'm trying to optimize the run-time of getting total credit and debt values out of our database. Ideally I'd like to formulate it as a Django query. This is the raw SQL query I have, which produces the right answer and is very fast (milliseconds): SELECT sum(tg.total) FROM ( SELECT sum