Django ORM传递模型方法总值

问题描述 投票:0回答:1

这是我的模特:

class Bill(models.Model):
    user =  models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='user_bill'
    )
    flat_rent = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0.00
    )
    gas_bill = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0.00
    )

    # Also i have many such decimalField here that calculated in get_total
    ===========================================


    def get_total(self):
        total = self.flat_rent + self.gas_bill
        return total

我正在尝试在此处传递此get_total Mehtod值:

user_wise = User.objects.filter(
            id=request.user.id
        ).aggregate(
            get_total=Sum('user_bill__get_total')
        )

就我而言,我必须用user查询related_name中的所有内容,这就是为什么我在此处汇总模型方法的原因。

任何人都可以帮助我如何在Agriggate中传递此get_total方法?

我不想这样通过。 Bill.objects.get(user__id=request.user.id).get_total

任何人都可以帮助实现这一目标吗?

感谢您的帮助

django django-models django-queryset django-orm
1个回答
0
投票

您可以这样简单地做:

from django.db.models import F, Sum

user_wise = Bill.objects.filter(
        user=request.user
    ).annotate(
        get_total=F('flat_rent') + F('gas_bill')
    ).aggregate(
        total=Sum('get_total')
    )
© www.soinside.com 2019 - 2024. All rights reserved.