Filtering on a relation problems

Issue #1141 resolved
Former user created an issue

I was trying to filter a child object based on its parent object id (see attached file). It seems that in case 2 the sql code that was generated is different than case 1 but there is no error/warning message. Case 3 fails with an AttributeError.

# CASE 1 - PASSED: result1 is a list of 2 children
result1 = q1.filter(Child.parent == p1).all()

# CASE 2 - FAILED: result2 is a list of 4 children (2 expected)
result2 = q1.filter(Parent.id == 1).all()

# CASE 3 - FAILED: 'InstrumentedAttribute' object has no attribute 'id'
result3 = q1.filter(Child.parent.id == 1).all()

Comments (2)

  1. Mike Bayer repo owner

    use case #2 and #3 should be:

    result2 = q1.join('parent').filter(Parent.id == 1).all()
    

    details on how to construct joins in SQLAlchemy are at http://www.sqlalchemy.org/docs/05/ormtutorial.html#datamapping_joins

    SQLA's Query lets you build any kind of SQL you'd like; it can't "guess" that the criterion you set up is not what you actually wanted. Calling a nonexistent attribute on an object (in this case Child.parent.id) raises an AttributeError in Python.

  2. Log in to comment