开发者

Want to Add all amounts for each country

Hello I have a django app dealing with Sales/purchases. What I want to do is add amounts depending on thier country type.

Looking at the sales table, there are two different country types. Uk and EU (I know EU is not a country but nevermind :) )

models.py

COUNTRY_TYPE_CHOICES = (
        (1, 'UK'),
        (2, 'EU'),
        )
class Sale(models.Model):
    country_type = models.IntegerField(verbose_name = "Location", choices = COUNTRY_TYPE_CHOICES)
    date = models.DateField()
    amount = models.DecimalField(max_digits=20, decimal_places=2)
    description =  models.TextField(max_length = 400)
    def __unicode__(self):
        return unicode(self.amount)

Now I want to display the amount of all sales. I want two results. The sum of all amount from the UK, and the sum of amount that are from the EU. I'm slight confused how you would add all amounts because of the two different choice types.

Here is also my views file which may help as well.

views.py

def home(request):
    sales = Sale.objects.all()
    return render_to_response('home.html', {'sales':sales}, context_instance=RequestContext(request))

Update: I have done so far

uk_sales = Sale.objects.filter(country_type='1')
开发者_如何学运维
{{uk_sales}}

On screen Gives me: <Sale: 467.99>, <Sale: 699.99>, <Sale: 499.99>]

Now It wold be good If I could add all these values. Not counting them.


from django.db.models import Sum
Sale.objects.values('country_type').annotate(Sum('amount')) 


This work quiet well for me.

uk_sales = Sale.objects.filter(country_type='1')
uk_amount = uk_sales.aggregate(price = Sum('amount'))['price']


If you are using Django 1.1 or newer, the you can use Django Aggregate Support with something like:

query_amount = Item.objects.extra(select={'sum': 'sum(amount)'}).values('sum', 'amount')
query_amount.query.group_by = ['country_type']

Here's Django official documentation on the topic. And here's a nice tutorial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜