Berislav Lopac
Berislav Lopac

Reputation: 17243

Django: how to filter on a 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_fee and owner_fee) from Unit.objects?

Upvotes: 6

Views: 3580

Answers (2)

okm
okm

Reputation: 23871

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

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

Upvotes: 17

San4ez
San4ez

Reputation: 8231

extra() can help you

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

Upvotes: 13

Related Questions