这是我的模特:
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多个领域。
所以我想在单行查询中了解所有这些字段的总数。
在这种情况下有人可以帮助我吗?
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')