我有三种型号:
class Customer(models.Model):
name = models.CharField(max_length=100)
class Transaction(models.Model):
debited_customer = models.ForeignKey(Customer, null=True, blank=True)
credited_customer = models.ForeignKey(Customer, null=True, blank=True)
amount_equ = models.BigIntegerField(null=True, blank=True)
class Account(models.Model):
customer = models.ForeignKey(Customer)
所有表名都是'pr_'+小写型号名称。有些客户没有账号。我想从所有交易中加上'amount_equ',其中debited_customer或credited_customer是有帐户的客户。我可以使用原始SQL查询来实现这一点:
SELECT SUM(tt.amount_equ)
FROM (SELECT DISTINCT t.id, amount_equ
FROM pr_transaction t INNER JOIN
(SELECT DISTINCT c.id
FROM pr_customer c INNER JOIN pr_account a ON c.id=a.customer_id) cc
ON t.debited_customer_id=cc.id OR t.credited_customer_id=cc.id) tt
没有原始sql可以做同样的事情吗?如何? 我试过了
Transaction.objects.filter(Q(credited_customer__account__isnull = False) | Q(debited_customer__account__isnull = False)).values('id').distinct()
并且它似乎提供了正确的交易集,但我不知道如何获得总和,我尝试.aggregate(Sum('amount_equ'))
但在这种情况下它采用不同的'amount_equ'而不是不同的pk,结果变为错