针对三种模型的django ORM查询
我有三种型号:针对三种模型的django ORM查询,django,postgresql,Django,Postgresql,我有三种型号: 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=Tru
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_u2;”+小写模型名。有些客户没有帐户。我想对所有交易的“金额”求和,其中借记客户或贷记客户都是有账户的客户。我可以通过原始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的情况下也可以这样做吗?怎么做?
我试过了
它似乎给出了正确的交易集,但我不知道如何获得总和,我尝试了
.aggregate(sum('amount_eq'))
,但在这种情况下,它采用了不同的'amount_eq',而不是不同的pk,结果变得错误为什么不允许在交易模型中使用负数?根据符号(+或-),您可以知道它是借方还是贷方。那样的话,汇总每个客户的总数是微不足道的。你不理解这个问题。这在我的项目中并不重要,无论金额是借方还是贷方,我不需要每个客户的金额。我需要的交易总额,其中至少有一个客户有一个帐户。无论如何,假设我在事务中有符号(+或-),请提供一个代码
Transaction.objects.filter(Q(credited_customer__account__isnull = False) | Q(debited_customer__account__isnull = False)).values('id').distinct()