0

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?

David542
  • 104,438
  • 178
  • 489
  • 842
  • Are you familiar with: https://docs.djangoproject.com/en/1.7/topics/db/aggregation/#generating-aggregates-over-a-queryset ? – Brandon Taylor Sep 15 '14 at 22:54

2 Answers2

1

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']
Community
  • 1
  • 1
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
1
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?

hd1
  • 33,938
  • 5
  • 80
  • 91