gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:21:50 24 4
gpt4 key购买 nike

这是我的 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'")

最佳答案

您可以将 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.

关于python - 如何在额外字段上过滤 Django 查询集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28313978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com