SQLAlchemy 不能用python的and作为查询连接符?

262 阅读1分钟

在SQLAlchemy中,可以使用and_作为查询连接符,但不能直接使用Python的and关键字。正确的方式是导入and_函数,并使用它来连接查询条件。

下面是一个例子:

from sqlalchemy import and_

results = db.query(SpShareholder).filter(
    and_(
        SpShareholder.merchant == query.ent,
        SpShareholder.snapshot_date == latest_snapshot_date
    )
).all()

注意,当你使用filter方法并且想要同时满足多个条件时,通常不需要显式使用and_,因为默认情况下filter将多个条件使用AND连接。以下代码与上面的示例等效:

results = db.query(SpShareholder).filter(
    SpShareholder.merchant == query.ent,
    SpShareholder.snapshot_date == latest_snapshot_date
).all()

使用&,并确保每个条件都用括号括起来,也是一种解决方案

db.query(SpShareholder).filter((SpShareholder.merchant == query.ent) & (SpShareholder.snapshot_date == latest_snapshot_date)).all()

所以,在SQLAlchemy的filter方法中使用Python的and关键字,而不是SQLAlchemy的and_函数或直接列出条件。这会导致查询的第二个条件被忽略,从而返回不正确的结果。