David542
David542

Reputation: 110083

Closest equivalent to SUM in Django

I have the following SQL query:

select SUM(royalty_price*conversion_to_usd)from sales_raw where date='2012-06-01'

The closest I was able to come up with in django is:

sum(SalesRaw.objects.extra(
        select={'result': 'royalty_price * conversion_to_usd'}
    ).values_list('result', flat=True))

Is there a more straightforward way to do this?

Upvotes: 0

Views: 47

Answers (2)

hd1
hd1

Reputation: 34657

from django.db.models import Manager
result = Manager.raw(u"""select SUM(royalty_price*conversion_to_usd)from sales_raw where date='2012-06-01'""")

Bearing in mind that django doesn't discourage you from using SQL, why not do so?

Upvotes: 1

Aamir Rind
Aamir Rind

Reputation: 39659

From answer by sha256 on this question, you can do something like this (not tested):

from django.db.models import Sum

result = SalesRaw.objects.filter(date='2012-06-01') \
    .aggregate(result=Sum('royalty_price', field='royalty_price*conversion_to_usd'))['result']

Upvotes: 1

Related Questions