Fra*_*tia 4 python postgresql sqlalchemy
我在 sqlalchemy 中遇到以下奇怪的行为。
Session.query(Player).filter(Player.name == 'Elijah Millsap').filter(Player.birth_date == None).first()
{name: Elijah Millsap, team: []}
Session.query(Player).filter(tuple_(Player.name, Player.birth_date).in_([('Elijah Millsap', None)])).all()
[]
Session.query(Player).filter(tuple_(Player.name, Player.birth_date).in_([('Elijah Millsap', None), ('Chris Bosh', '1984-03-24')])).all()
[{name: Chris Bosh, team: []}]
Run Code Online (Sandbox Code Playgroud)
使用 tuple_ 查询时,colbirth_date 为 null 的行似乎失败
这不起作用,因为与NULLSQL 中的比较是IS NULL. 比较= NULL产生的NULL不是布尔值 true 或 false。
在 SQLAlchemy 中,比较== None被转换为IS NULL,但是当您使用直接放入值列表中的in_gets时NULL,导致 RDBMS 将其计算为= NULL,而不是IS NULL。
不幸的是,在这种情况下,解决方案并不理想。您必须取出None其中包含 s 的元组并执行or_. 例子:
.filter(or_(tuple_(Player.name, Player.birth_date).in_([('Chris Bosh', '1984-03-24')]),
and_(Player.name.in_(['Elijah Millsap']), Player.birth_date.is_(None))))
Run Code Online (Sandbox Code Playgroud)