Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 513
Berislav Lopac Avatar asked May 19 '12 08:05

Berislav Lopac


People also ask

Can we use multiple filters in Django?

I always assumed that chaining multiple filter() calls in Django was always the same as collecting them in a single call. The first queryset with the chained filter() calls joins the Inventory model twice effectively creating an OR between the two conditions whereas the second queryset ANDs the two conditions together.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is the difference between GET and filter in Django?

Returns a new QuerySet containing objects that match the given lookup parameters. Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.

What does objects all () do in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.


1 Answers

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'))
like image 69
okm Avatar answered Sep 20 '22 01:09

okm