为什么 peewee 没有正确嵌套这个 WHERE 子句?
Why is peewee not nesting this WHERE clause correctly?
我正在 Python peewee ORM:
中创建这样的查询
myTableModel.records = myTableModel.select(
myTableModel.table_field_name
).where(
(myTableModel.second_field_name.is_null(True) |
myTableModel.second_field_name == "")
)
我可以回到 运行 print myTableModel.records.sql()
生成的 SQL
SELECT `t1`.`table_field_name`
FROM `table_name` AS t1
WHERE (((`t1`.`second_field_name` IS NULL) OR `t1`.`second_field_name`) = '');
这没有使用正确的嵌套。这是我想要的声明:
SELECT `t1`.`table_field_name`
FROM `table_name` AS t1
WHERE `t1`.`second_field_name` IS NULL OR `t1`.`second_field_name` = '';
现有的 WHERE
子句归结为...
WHERE `t1`.`second_field_name` IS NULL = ''
... 产生与我想要的完全相反的结果,返回所有 second_field_name
为 not NULL
.
的行
我该如何解决这个问题?我是否以某种方式错误地嵌套了 Python 代码?
通过反复试验,我发现再添加两个括号可以修复查询。必须在 myTableModel.second_field_name == ""
周围添加括号,如下所示:
myTableModel.records = myTableModel.select(
myTableModel.table_field_name
).where(
(myTableModel.second_field_name.is_null(True) |
(myTableModel.second_field_name == ""))
)
我不确定这到底有什么帮助。似乎 Python 和 peewee 应该能够使用竖线和外括号作为分隔符。
Peewee 依靠 Python 的解析器来生成表达式。由于 Python 的 operator precedence,大多数比较都需要括号。这里没有魔法,只是 Python.
http://docs.peewee-orm.com/en/latest/peewee/querying.html?highlight=precedence#expressions
我正在 Python peewee ORM:
中创建这样的查询myTableModel.records = myTableModel.select(
myTableModel.table_field_name
).where(
(myTableModel.second_field_name.is_null(True) |
myTableModel.second_field_name == "")
)
我可以回到 运行 print myTableModel.records.sql()
SELECT `t1`.`table_field_name`
FROM `table_name` AS t1
WHERE (((`t1`.`second_field_name` IS NULL) OR `t1`.`second_field_name`) = '');
这没有使用正确的嵌套。这是我想要的声明:
SELECT `t1`.`table_field_name`
FROM `table_name` AS t1
WHERE `t1`.`second_field_name` IS NULL OR `t1`.`second_field_name` = '';
现有的 WHERE
子句归结为...
WHERE `t1`.`second_field_name` IS NULL = ''
... 产生与我想要的完全相反的结果,返回所有 second_field_name
为 not NULL
.
我该如何解决这个问题?我是否以某种方式错误地嵌套了 Python 代码?
通过反复试验,我发现再添加两个括号可以修复查询。必须在 myTableModel.second_field_name == ""
周围添加括号,如下所示:
myTableModel.records = myTableModel.select(
myTableModel.table_field_name
).where(
(myTableModel.second_field_name.is_null(True) |
(myTableModel.second_field_name == ""))
)
我不确定这到底有什么帮助。似乎 Python 和 peewee 应该能够使用竖线和外括号作为分隔符。
Peewee 依靠 Python 的解析器来生成表达式。由于 Python 的 operator precedence,大多数比较都需要括号。这里没有魔法,只是 Python.
http://docs.peewee-orm.com/en/latest/peewee/querying.html?highlight=precedence#expressions