序言:
这是一个经常在SO上出现的问题:
- Subtracting two annotated columns
- Django query with simple arithmetic among model fields and comparison with field from another model
- Django Aggregation: Summation of Multiplication of two fields
它也可以应用于在这里:
我已经在SO文档中编写了一个示例,但由于该文档将于2017年8月8日关闭,因此我将遵循这个广泛赞同和讨论的元回答的建议,并将我的示例转换为自我回答的帖子。
当然,我非常乐意看到任何不同的方法!!
问题:
假设以下模型:
class MyModel(models.Model):
number_1 = models.IntegerField()
number_2 = models.IntegerField()
date_1 = models.DateTimeField()
date_2 = models.DateTimeField()
我怎样才能在该模型的字段之间执行算术运算?
例如,我怎么找到:
- MyModel对象的
number_1
和number_2
的积? - 如何筛选
date_2
比date_1
早10天或更多的项目?