Django ORM对模型类的所有字段值求和

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

这是我的模特:

class Bill(models.Model):
    user =  models.OneToOneField(
        User,
        on_delete=models.CASCADE,

    )
    flat_rent = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        null=True,
        blank=True
    )
    gas = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        null=True,
        blank=True
    )

我知道一种方法,但我不喜欢这样:喜欢

bill = Bill.objects.get(--------)
total = bill.gas + bill.flat_rent

但是我认为这是不好的做法,因为我在这个模型中有20多个领域。

所以我想在单行查询中了解所有这些字段的总数。

在这种情况下有人可以帮助我吗?

django django-models django-orm
1个回答
0
投票
您可以像这样使用F()函数:

field_names = [field.name for field in Bill._meta.get_fields()] # remove unwanted fields from field_names, if any expr = reduce(add, (F(field) for field in field_names)) Bill.objects.filter(---).annotate(total=expr).values('total')

© www.soinside.com 2019 - 2024. All rights reserved.