How to execute arithmetic operations between Model fields in django

Viewed 9276

Prologue:

This is a question arising often in SO:

And can also be applied here:

I have composed an example on SO Documentation but since the Documentation will get shut down on August 8, 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post.

Of course, I would be more than happy to see any different approach as well!!


Question:

Assume the following model:

class MyModel(models.Model):
    number_1 = models.IntegerField()
    number_2 = models.IntegerField()
    date_1 = models.DateTimeField()
    date_2 = models.DateTimeField()

How can I execute arithmetic operations between fields of this model?

For example, how can I find:

  • The product of number_1 and number_2 of a MyModel object?
  • How to filter items where date_2 is 10 or more days older than date_1?
1 Answers
Related