filter_by danger if accidentally using "and"

Issue #3545 resolved
B. Candler created an issue

There is some dangerous behaviour with filter_by which I think warrants a warning in the documentation. [Tested with SQLAlchemy 0.9.9]

# WRONG
Foo.filter_by(Foo.ref == ref and Foo.type == type and Foo.tag == tag)

# RIGHT
Foo.filter_by(Foo.ref == ref, Foo.type == type, Foo.tag == tag)
Foo.filter_by((Foo.ref == ref) & (Foo.type == type) & (Foo.tag == tag))
from sqlalchemy import and_
Foo.filter_by(and_(Foo.ref == ref, Foo.type == type, Foo.tag == tag))

The incorrect form is silently accepted and apparently works, but actually behaves the same as Foo.filter_by(Foo.ref == ref) i.e. part of the query you expected to be generated is quietly dropped off.

At http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html it says:

"Multiple criteria are joined together by AND:"

followed by a valid example, but I think it should clarify that you don't actually use the python "and" operator.

Comments (6)

  1. Mike Bayer repo owner
    • remove ambiguous use of the phrase "joined together by AND" as this may be construed as the Python "and" keyword
    • add notes to ORM tutorial for beginners that Python "and" keyword is not to be used fixes #3545

    → <<cset ac0892028493>>

  2. Log in to comment