简体   繁体   English

Sqlalchemy两个过滤器与一个和

[英]Sqlalchemy two filters vs one and

This is a straight forward question. 这是一个直截了当的问题。 What is better to use, two filters or one and_ ? 什么是更好的使用,两个filters或一个and_ _? Is there any difference? 有什么区别吗?

session.query(Test).filter(Test.id == X).filter(Test.test == Y).all()

vs VS

session.query(Test).filter(and_(Test.id == X, Test.test == Y)).all()

They will give me the same result but is there any difference i speed or anything else? 他们会给我相同的结果,但速度或其他任何东西有什么不同吗?

Both queries in your question have the same performance. 您问题中的两个查询都具有相同的性能。 You can test this easily by inspecting the resulting SQL query. 您可以通过检查生成的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

Both queries produce the same SQL expression. 两个查询都生成相同的SQL表达式。

and_ is commonly used when you're using the SQL expression to query directly against tables, or when nesting multiple predicates within or_ . and_当你使用SQL表达式直接对表进行查询,或者嵌套在多个谓词时,通常使用or_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM