I'm creating a query like this in the Python peewee ORM:
myTableModel.records = myTableModel.select(
myTableModel.table_field_name
).where(
(myTableModel.second_field_name.is_null(True) |
myTableModel.second_field_name == "")
)
I can work back to the SQL generated by running 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`) = '');
This is not using the correct nesting. This is the statement I want:
SELECT `t1`.`table_field_name`
FROM `table_name` AS t1
WHERE `t1`.`second_field_name` IS NULL OR `t1`.`second_field_name` = '';
The existing WHERE
clause boils down to this ...
WHERE `t1`.`second_field_name` IS NULL = ''
... which produces exactly the opposite of what I want, returning all rows where second_field_name
is not NULL
.
How do I fix this? Did I nest the Python code incorrectly somehow?
Through trial and error, I've found that adding two more parentheses fixes the query. Parentheses must be added around myTableModel.second_field_name == ""
like so:
myTableModel.records = myTableModel.select(
myTableModel.table_field_name
).where(
(myTableModel.second_field_name.is_null(True) |
(myTableModel.second_field_name == ""))
)
I'm not sure exactly why this helps. It seems like Python and peewee ought to be able to use the pipe and outer parentheses as delimiters.