As an example, I have a cities table and a movie theaters table. A city has multiple movie theaters so:
JavaScript
x
12
12
1
class City(Base):
2
__tablename__ = 'cities'
3
id = Column(Integer, primary_key=True)
4
name = Column(VARCHAR(255))
5
theaters = relationship("Theater", backref=backref("theaters"))
6
7
class Theater(Base):
8
__tablename__ = 'theaters'
9
id = Column(Integer, primary_key=True)
10
city_id = Column(Integer, ForeignKey('cities.id'))
11
name = Column(VARCHAR(255), nullable=False)
12
now i want to get all theaters for a city:
JavaScript
1
2
1
theaters = db_session.query(City).filter_by(city = "New York").join(Theater.city_id).all()
2
This query throws error:
JavaScript
1
2
1
sqlalchemy.exc.ArgumentError: Join target Theater.city_id does not refer to a mapped entity
2
not sure what I’m doing wrong?
Advertisement
Answer
Something like this should automatically do the join for you:
JavaScript
1
18
18
1
class City(Base):
2
__tablename__ = 'cities'
3
id = Column(Integer, primary_key=True)
4
name = Column(VARCHAR(255))
5
theaters = relationship(
6
"Theater",
7
lazy='joined',
8
backref=backref("city") # This is how you refer to the city
9
# from theater. In other words, this adds
10
# a field "city" to the Theater class.
11
)
12
13
class Theater(Base):
14
__tablename__ = 'theaters'
15
id = Column(Integer, primary_key=True)
16
city_id = Column(Integer, ForeignKey('cities.id'))
17
name = Column(VARCHAR(255), nullable=False)
18
And then the query would be
JavaScript
1
2
1
ny_theaters = session.query(Theater).filter(Theater.city.has(City.name == 'New York')).all()
2
Make sense?