Django: how to filter by the sum of two fields in a related model?

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_feeand owner_fee) from Unit.objects?

+5
source share
2 answers

extra() can help you

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

Or just convert a + b > cto a > c - bto use the models.Fexpression :

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

All Articles