Sqlalchemy 两个过滤器与一个过滤器

kem*_*mis 7 python sqlalchemy

这是一个直截了当的问题。两个filters或一个哪个更好用and_?有什么区别吗?

session.query(Test).filter(Test.id == X).filter(Test.test == Y).all()
Run Code Online (Sandbox Code Playgroud)

对比

session.query(Test).filter(and_(Test.id == X, Test.test == Y)).all()
Run Code Online (Sandbox Code Playgroud)

他们会给我相同的结果,但我的速度或其他任何东西有什么不同吗?

Iva*_*hoo 9

您问题中的两个查询具有相同的性能。您可以通过检查生成的 SQL 查询轻松测试这一点。

from sqlalchemy import Column, Integer, String, and_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.query import Query

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    test = Column(String(50))


print(Query([Test]).filter(Test.id == 1).filter(Test.test == 'foo'))

# SELECT test.id AS test_id, test.test AS test_test
# FROM test
# WHERE test.id = :id_1 AND test.test = :test_1

print(Query([Test]).filter(and_(Test.id == 1, Test.test == 'foo')))

# SELECT test.id AS test_id, test.test AS test_test
# FROM test
# WHERE test.id = :id_1 AND test.test = :test_1
Run Code Online (Sandbox Code Playgroud)

两个查询都生成相同的 SQL 表达式。

and_当你使用SQL表达式查询直接对表或嵌套内的多个谓词时,通常使用or_