【发布时间】: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