Django Execute Arithmetic operations between fields


Example

F() expressions can be used to execute arithmetic operations (+, -, * etc.) among model fields, in order to define an algebraic lookup/connection between them.

  • Let model be:

    class MyModel(models.Model):
        int_1 = models.IntegerField()
        int_2 = models.IntegerField()
    
  • Now lets assume that we want to retrieve all the objects of MyModel table who's int_1 and int_2 fields satisfy this equation: int_1 + int_2 >= 5. Utilizing annotate() and filter() we get:

    result = MyModel.objects.annotate(
                 diff=F(int_1) + F(int_2)
             ).filter(diff__gte=5)
    

    result now contains all of the aforementioned objects.

Although the example utilizes Integer fields, this method will work on every field on which an arithmetic operation can be applied.