Django加总

时间:2018-09-21 21:05:10

标签: django database orm

我有两个模型,Transaction和TransactionType。

class Transaction(models.Model):
    tran_date = models.DateField()
    tran_amount = models.FloatField(default=0.00)
    tran_payment_method = models.ForeignKey(PaymentMethod,on_delete=models.SET_NULL,null=True)
    tran_location = models.ForeignKey(Location,on_delete=models.SET_NULL,null=True)
    tran_type = models.ForeignKey(TransactionType,on_delete=models.SET_NULL,null=True)
    account = models.ForeignKey(User,on_delete=models.CASCADE,default='')
    create_date = models.DateTimeField(auto_now_add=True, blank=True)

class TransactionType(models.Model):
    name = models.CharField(max_length=200)
    status = models.IntegerField(default=1)  # 0:inactive 1:active
    income_ind=models.IntegerField(default=0) # 1: expense 2: income
    account = models.ForeignKey(User, on_delete=models.CASCADE,default='')
    create_date = models.DateTimeField(auto_now_add=True, blank=True)

我想使用ORM来运行如下查询

select b.name,sum(a.tran_amount) as total
from Transaction a
inner join TransactionType b
on a.tran_type = b.id
where a.account=some_user_id and b.income_ind=1

如何在不使用原始查询的情况下实现此目的?

1 个答案:

答案 0 :(得分:0)

如果TransactionType.name是唯一的(因此没有两个具有相同名称的TransactionType),那么我们可以使用.annotate(..)

from django.db.models import Sum

TransactionType.objects.filter(
    transaction__acount_id=some_user_id
    income_ind=1
).annotate(
    total=Sum('transaction__tran_amount')
)

这将导致一个QuerySet包含TransactionType,并且每个TransactionType都将具有一个total的属性tran_amount Transactionacount_id(要填写)的相关some_user_id

此外,我们仅考虑TransactionTypeincome_ind的{​​{1}}个。