如何对 Django 模型的一对多相关字段执行条件聚合?

How to perform conditional aggregation on a Django model's one to many related field?

给定以下模型架构:

class Transaction(models.Model):
  wallet = models.ForeignKey(related_name="transactions")
  amount = models.DecimalField()  # must be positive value
  type = models.CharField(choices=[("deposit", "deposit"), ("withdrawal", "withdrawal")]

class Wallet(models.Model):
  pass

获取数据库中每条钱包记录余额的最有效的 Django ORM 查询是什么?

current_balance = sum of "amounts", where type="deposits" - sum of "amounts", where type="withdrawal"

假设我们无法更改给定表/记录的列或字段,并且 amount 必须保持正值。

想法?

也许我们可以合作:

from django.db.models import Sum

Wallet.objects.annotate(
    balance=Sum('transactions__amount', <strong>filter=Q(transactions__type='deposit')</strong>) -
            Sum('transactions__amount', <strong>filter=Q(transactions__type='withdrawal')</strong>)
)

但我建议在提款的情况下将金额设为负数,在这种情况下我们可以简单地总结交易:

# when using negative amounts for withdrawals

from django.db.models import Sum

Wallet.objects.annotate(
    balance=Sum('transactions__amount')
)