如何根据 django 模型中字段的比较值进行过滤?

How to filter based on compared values of fields in a model in django?

如何根据比较任何模型中字段的内部值来过滤查询集?

例如,请看下面的示例:

class Model1(models.Model):
    num1 = models.IntegerField()
    num2 = models.IntegerField()

假设我必须筛选出 num2 - num1 小于 10 的 Model1 值。 那么,我们将如何编写过滤条件呢? 即Model1.objects.filter(???)?

另外,假设字段是日期时间,如下所示:

class Model2(models.Model):
    t1 = models.DateTimeField(auto_now_add=True)
    t2 = models.DateTimeField()

我们如何实现与上述类似的案例。假设我们要根据小于 10 小时的 t2-t1 进行过滤?

您可以对计算进行注释,然后根据结果进行过滤。

from django.db.models import F
Model1.objects.annotate(diff=F('num1')-F('num2')).filter(diff__lt=10)