我正在尝试编写一个ORM查询,以便在聚合后将一个表与其自身连接起来(因此select_related
等将不起作用)。简单的SQL查询是在表transaction
中使用的字段(account_id,金额,booking_date,参考,...)
select * from
transaction t
join
(
select account_id, sum(amount) as total_amount
from transaction
where amount > 0
group by account_id
) aggr
on t.account_id = aggr.account_id
where amount > 0.4 * total_amount;
到目前为止没有运气。我什至尝试了join_to/CustomJoin
中的Django ORM. Joining subquery,但这没有用。
编辑。型号如下
class Account(models.Model):
currency = models.CharField(max_length=30)
...
class Transaction(models.Model):
account = models.ForeignKey(Account, db_constraint=False)
amount = models.DecimalField(max_digits=10, decimal_places=2)
booking_date = models.DateTimeField(db_index=True)
...
鉴于Transaction
对ForeignKey
模型具有Account
,您可以使用以下方式进行这样的查询:
from django.db.models import F, Sum
Transaction.objects.annotate(
total_amount=Sum(
'account__transaction__amount',
filter=Q(account__transaction__amount__gt=0)
)
).filter(
amount__gt=0.4*F('total_amount')
)