如何在额外字段上过滤 Django 查询集?

How can I filter a Django Queryset on an extra field?

这是我的 Django 模型:

from django.db import models
class MyModel(models.Model):
    a = models.IntegerField()
    b = models.IntegerField()
    c = models.IntegerField()

我想检索此模型的所有实例,其中 a = 5b + c > 10。我该怎么做?

当我尝试这个时:

print MyModel.objects.filter(a=5).extra(
    select={"total_count": "b + c"},
    where=["total_count > 10"],
)

我收到这个错误:

OperationalError: (1054, "Unknown column 'total_count' in 'where clause'")

在 django 1.7 中,此过滤器工作正常并生成以下查询:

SELECT (b + c) AS "total_count", "app_mymodel"."id", "app_mymodel"."a",
       "app_mymodel"."b", "app_mymodel"."c" 
FROM "app_mymodel"
WHERE ("app_mymodel"."a" = 5 AND (total_count > 10))

你能用真实的字段名复制你的查询吗?可能是你打错了什么地方?

您可以将b + c > 10转换为b > 10 - c,然后使用F built-in function

MyModel.objects.filter(a=5).filter((b__gt=10-models.F('c'))

使用 Django extra() 不太安全

You should be very careful whenever you use extra(). Every time you use it, you should escape any parameters that the user can control by using params in order to protect against SQL injection attacks . Please read more about SQL injection protection.