This is a straight forward question. What is better to use, two filters
or one and_
? Is there any difference?
session.query(Test).filter(Test.id == X).filter(Test.test == Y).all()
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.
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.
and_ is commonly used when you're using the SQL expression to query directly against tables, or when nesting multiple predicates within or_
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With