【问题标题】:Error in Calculating the sum of a filtered column value using Django Queries使用 Django 查询计算过滤列值的总和时出错
【发布时间】:2020-12-25 01:02:46
【问题描述】:

我有 2 个模型

class Horses(models.Model):
race = models.IntegerField(null=True)
name = models.CharField(max_length=200, null=True)
owners = models.ManyToManyField(Owners)

class BetOrders(models.Model):
customers =models.ForeignKey(Customers, null = True, on_delete=models.SET_NULL)
horses = models.ForeignKey(Horses, null = True, on_delete=models.SET_NULL)
amountBet = models.FloatField(null = True)
horseprice = models.IntegerField(null=True)
timeOfBet = models.DateTimeField(auto_now_add = True, null = True)

我正在尝试根据相似的马名计算amountBet 的总和。 我已经尝试过这个查询集,但没有成功

BetOrders.objects.filter(horses__name='white river').annotate(total_sales=Sum('amountBet'))

我可以知道这个查询有什么问题吗?以及获得过滤值总和的正确方法是什么。 注意:马名是 FK。 这是我的表的表示

+-------+------------------+
| Horse Name  | Amount Bet |
+-------------+------------+
| jals jiger  |    50      |
| white river |    80      |
| white river |    70      |
| jals jiger  |    10      |
| jals jiger  |    98      |
| chivas      |    10      |
+-------------+------------+

【问题讨论】:

    标签: python django django-queryset aggregation


    【解决方案1】:

    在进行 Group By 查询时,您需要使用 .values() 和 .annotate() 来触发“Group By”。试试下面的:

    BetOrders.objects.values('horses__name').annotate(total_sales=Sum('amountBet')).filter(horses__name='white river')
    

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 2022-01-04
      • 2013-06-11
      • 1970-01-01
      • 2019-07-12
      • 2019-03-26
      • 2012-03-07
      • 1970-01-01
      • 2020-06-29
      相关资源
      最近更新 更多