【问题标题】:Querying a table from another table using SQLAlchemy使用 SQLAlchemy 从另一个表中查询一个表
【发布时间】:2020-06-08 10:30:40
【问题描述】:

我是使用 SQLAlchemy、Python 和 Flask 编程和学习关系数据库的新手。

我想知道它是否可能,如果可能,如何获取引用一个连接到多个其他表的信息。例如,我将下表连接到另一个(使用 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))

除了直接查询类模型Vlocation,像这样:db.session.query(Vlocation.city, Vlocation.state).all(),有没有办法通过查询类模型Venue得到这个信息?我试过这个: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'。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python flask sqlalchemy flask-sqlalchemy psql


    【解决方案1】:

    也许你可以试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2020-06-14
      • 2016-07-13
      相关资源
      最近更新 更多