【问题标题】:Django sum of a particular field for some distinct column某些不同列的特定字段的 Django 总和
【发布时间】:2022-07-27 03:43:06
【问题描述】:

我有一个表 OrderTransaction,其中有表 Order 的外键。我想计算未结金额,即尚未发生交易的金额。要计算,我首先需要计算总金额(订单表有字段总金额),以便我可以从中减去已发生的交易金额。我按 recorded_by 字段的查询进行分组,因为我需要知道哪个推销员收集了多少金额。以下是我的查询。

order_transaction_qs
.exclude(recorded_by=None)
.order_by("recorded_by")
.values("recorded_by")
.annotate(
    cash_in_hand=Coalesce(
        Sum("amount", filter=Q(payment_method=PaymentMethod.CASH_ON_DELIVERY)), Value(0)
    ),
    cheque=Coalesce(
        Sum("amount", filter=Q(payment_method=PaymentMethod.CHEQUE)), Value(0)
    ),
    others=Coalesce(
        Sum(
            "amount",
            filter=~Q(
                payment_method__in=[
                    PaymentMethod.CHEQUE,
                    PaymentMethod.CASH_ON_DELIVERY,
                ]
            ),
        ),
        Value(0),
    ),
    order_amount=Sum(
        "order__total_amount"
    ),  # NOTE: Multiple transactions on same orders will give extra amount.
    outstanding=ExpressionWrapper(
        F("order_amount") - (F("cash_in_hand") + F("cheque") + F("others")),
        output_field=FloatField(),
    ),
)

上述查询的问题是,如果同一订单有多个交易,它会多次添加total_amount。 请建议我该怎么做。

【问题讨论】:

    标签: python django database django-models


    【解决方案1】:

    将多个聚合与 annotate() 组合会产生错误的结果,因为根据 django 文档:https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#combining-multiple-aggregations

    使用连接而不是子查询

    这篇文章分享了一个类似问题的解决方案:Django multiple annotate with Sum get wrong answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多