使用 SQLAlchemy 从另一个 table 查询一个 table

Querying a table from another table using SQLAlchemy

我不熟悉使用 SQLAlchemy、Python 和 Flask 进行关系数据库编程和学习。

我想知道这是否可行,如果可行,如何获取引用一个 table 的信息,该 table 与其他多个相连。例如,我将以下 table 连接到另一个(使用 SQLAlchemy):

class Venue(db.Model):
    __tablename__ = 'venue'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(25), unique=True)
    location = db.relationship('Vlocation', backref='venue', cascade='all', lazy='dynamic')

    def __rep__(self):
        f'Venue: <{self.id}, {self.name}>'

class Vlocation(db.Model):
  __tablename__ = 'vlocation'

  id = db.Column(db.Integer, primary_key=True)
  venue_id = db.Column(db.Integer, db.ForeignKey('venue.id', ondelete='CASCADE'), nullable=False)
  address = db.Column(db.String(120))
  city = db.Column(db.String(120))
  state = db.Column(db.String(3))

除了直接查询class模型Vlocation,像这样:db.session.query(Vlocation.city, Vlocation.state).all(),有没有办法通过查询class模型[=15]来获取这些信息=]?我试过这个:db.session.query(Venue.location.city, Venue.location.state).all(),但我收到以下错误:AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Venue.location has an attribute 'city'。有更好的方法吗?

也许你可以试试这个

vlocations = []
for venue in Venue.query.all():
    vlocations.extened(venue.location)
vlocations = list(set(vlocations))