Django:如何过滤相关模型中两个字段的总和?

时间:2022-08-28 20:29:52

I have a model basically like this:

我的模型基本上是这样的:

class Unit(models.Model):
    name = models.CharField(max_length=64)

class UnitPrice(models.Model):
    unit       = models.ForeignKey(Unit, related_name="prices")
    agency_fee = models.DecimalField(default=0.0, max_digits=7, decimal_places=2)
    owner_fee  = models.DecimalField(default=0.0, max_digits=7, decimal_places=2)
    def amount(self):
        return self.owner_fee + self.agency_fee

Is there a way to filter for amount (i.e. the sum of agency_fee and owner_fee) from Unit.objects?

有没有办法从Unit.objects过滤金额(即agency_fee和owner_fee的总和)?

2 个解决方案

#1


10  

extra() can help you

extra()可以帮到你

UnitPrice.objects.extra(where=["agency_fee + owner_fee > 10"])

#2


15  

Or simply transform a + b > c to a > c - b in order to use models.F expression:

或者简单地将a + b> c转换为a> c - b以便使用models.F表达式:

UnitPrice.objects.filter(agency_fee__gt=10-models.F('owner_fee'))

#1


10  

extra() can help you

extra()可以帮到你

UnitPrice.objects.extra(where=["agency_fee + owner_fee > 10"])

#2


15  

Or simply transform a + b > c to a > c - b in order to use models.F expression:

或者简单地将a + b> c转换为a> c - b以便使用models.F表达式:

UnitPrice.objects.filter(agency_fee__gt=10-models.F('owner_fee'))