尝试使用 SQLAlchemy 关系
Trying to use SQLAlchemy relationships
例如,我有一个城市 table 和一个电影院 table。一个城市有多个电影院所以:
class City(Base):
__tablename__ = 'cities'
id = Column(Integer, primary_key=True)
name = Column(VARCHAR(255))
theaters = relationship("Theater", backref=backref("theaters"))
class Theater(Base):
__tablename__ = 'theaters'
id = Column(Integer, primary_key=True)
city_id = Column(Integer, ForeignKey('cities.id'))
name = Column(VARCHAR(255), nullable=False)
现在我想获取一个城市的所有影院:
theaters = db_session.query(City).filter_by(city = "New York").join(Theater.city_id).all()
此查询抛出错误:
sqlalchemy.exc.ArgumentError: Join target Theater.city_id does not refer to a mapped entity
不确定我做错了什么?
像这样的东西应该会自动为你做连接:
class City(Base):
__tablename__ = 'cities'
id = Column(Integer, primary_key=True)
name = Column(VARCHAR(255))
theaters = relationship(
"Theater",
lazy='joined',
backref=backref("city") # This is how you refer to the city
# from theater. In other words, this adds
# a field "city" to the Theater class.
)
class Theater(Base):
__tablename__ = 'theaters'
id = Column(Integer, primary_key=True)
city_id = Column(Integer, ForeignKey('cities.id'))
name = Column(VARCHAR(255), nullable=False)
然后查询将是
ny_theaters = session.query(Theater).filter(Theater.city.has(City.name == 'New York')).all()
有道理吗?
theaters = db_session.query(Theater).join(City).filter(City.name = "New York").all()
例如,我有一个城市 table 和一个电影院 table。一个城市有多个电影院所以:
class City(Base):
__tablename__ = 'cities'
id = Column(Integer, primary_key=True)
name = Column(VARCHAR(255))
theaters = relationship("Theater", backref=backref("theaters"))
class Theater(Base):
__tablename__ = 'theaters'
id = Column(Integer, primary_key=True)
city_id = Column(Integer, ForeignKey('cities.id'))
name = Column(VARCHAR(255), nullable=False)
现在我想获取一个城市的所有影院:
theaters = db_session.query(City).filter_by(city = "New York").join(Theater.city_id).all()
此查询抛出错误:
sqlalchemy.exc.ArgumentError: Join target Theater.city_id does not refer to a mapped entity
不确定我做错了什么?
像这样的东西应该会自动为你做连接:
class City(Base):
__tablename__ = 'cities'
id = Column(Integer, primary_key=True)
name = Column(VARCHAR(255))
theaters = relationship(
"Theater",
lazy='joined',
backref=backref("city") # This is how you refer to the city
# from theater. In other words, this adds
# a field "city" to the Theater class.
)
class Theater(Base):
__tablename__ = 'theaters'
id = Column(Integer, primary_key=True)
city_id = Column(Integer, ForeignKey('cities.id'))
name = Column(VARCHAR(255), nullable=False)
然后查询将是
ny_theaters = session.query(Theater).filter(Theater.city.has(City.name == 'New York')).all()
有道理吗?
theaters = db_session.query(Theater).join(City).filter(City.name = "New York").all()