【问题标题】:Want to Add all amounts for each country想要添加每个国家/地区的所有金额
【发布时间】:2011-09-18 13:11:44
【问题描述】:

您好,我有一个处理销售/采购的 django 应用程序。我想要做的是根据他们的国家类型添加金额。

查看销售表,有两种不同的国家/地区类型。英国和欧盟(我知道欧盟不是一个国家,但没关系:))

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)

现在我想显示所有销售额的amount。我想要两个结果。来自英国的所有amount 的总和,以及来自欧盟的amount 的总和。由于两种不同的选择类型,我有点困惑如何添加所有金额。

这也是我的视图文件,它也可能有所帮助。

views.py

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

更新:到目前为止我已经完成了

uk_sales = Sale.objects.filter(country_type='1')

{{uk_sales}}

屏幕上给我:<Sale: 467.99>, <Sale: 699.99>, <Sale: 499.99>]

现在,如果我可以添加所有这些值,那就太好了。不算他们。

【问题讨论】:

    标签: python django sum add


    【解决方案1】:
    from django.db.models import Sum
    Sale.objects.values('country_type').annotate(Sum('amount')) 
    

    【讨论】:

    • @daniel: 有没有办法只打印数字?目前,您的方法将打印在屏幕上:[{'country_type': 1L, 'amount__sum': Decimal('1499.97')}, {'country_type': 2L, 'amount__sum': Decimal('1000.00')}]。例如,我只想要“1499.97”和“1000.00”。
    • 来吧,你已经在这个网站上提问十个月了,你现在肯定知道足够的 Python 来遍历列表并从字典中选择值。
    【解决方案2】:

    这项工作对我来说很安静。

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

    【讨论】:

      【解决方案3】:

      如果您使用的是 Django 1.1 或更新版本,您可以使用 Django Aggregate Support,例如:

      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 topicAnd here's a nice tutorial.

      【讨论】:

      • 这个答案不使用聚合函数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      相关资源
      最近更新 更多