【问题标题】:Django get the sum of all columns for a particular userDjango 获取特定用户的所有列的总和
【发布时间】:2021-06-13 08:31:01
【问题描述】:

我有一个 django 模型如下:

class Order(models.Model):
    cash=models.DecimalField(max_digits=11,decimal_places=2,default=0)
    balance=models.DecimalField(max_digits=11,decimal_places=2,default=0)
    current_ac=models.DecimalField(max_digits=11,decimal_places=2,default=0)   
    added_by = models.ForeignKey(User)

可以有多个订单,多个用户可以创建订单。

如何获取特定用户每列的所有订单总和,例如

ord=Order.objects.filter(added_by.id=1).sum()

SQL 等价物类似于

Select sum(cash), sum (balance), sum(current_ac) from Orders where added_by = 1

【问题讨论】:

  • 您要对哪一列求和? current_accash?
  • 所有这些。假设有 2 个订单订单 1 和 2,现金 3 和 5,余额 1 和 2,当前 ac 3 和 4。我希望输出是 Order 对象,其中现金 8,余额 3 和当前 ac 7 作为值。跨度>
  • 查看编辑后的答案。

标签: python django django-models


【解决方案1】:

如果我理解正确的话。你想计算记录的数量,对吧?如果是这样的话。您可以使用过滤器和计数。如下例所示:

numberOfRecords = Orders.filter(added_by=user_id).count

【讨论】:

    【解决方案2】:

    您可以聚合,例如current_ac 的总和:

    from decimal import Decimal
    from django.db.models import Sum
    
    ord=Order.objects.filter(added_by_id=1).aggregate(
        total=Sum('current_ac')
    )['total'] or Decimal()

    或者如果你想总结cashbalancecurrent_ac的项目,你可以使用:

    from decimal import Decimal
    from django.db.models import Sum
    
    ord=Order.objects.filter(added_by_id=1).aggregate(
        total_cash=Sum('current_ac'),
        total_balance=Sum('balance'),
        total_ac=Sum('current_ac')
    )

    这里ord将是一个包含相应值的字典,例如:

    {
      'total_cash': Decimal('14.25'),
      'total_balance': Decimal('13.02'),
      'total_ac': Decimal('17.89')
    }
    

    或者如果你想计算Orders的数量,那么我们可以使用:

    from decimal import Decimal
    
    ord=Order.objects.filter(added_by_id=1).count()

    如果你想这样做per User,使用.annotate(…) [Django-doc] 会更有效率。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多