[英]Querying a table from another table using SQLAlchemy
我是使用 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))
Besides directly querying the class model Vlocation
, like this: db.session.query(Vlocation.city, Vlocation.state).all()
, is there a way to get this information by querying the class model Venue
? I tried this: db.session.query(Venue.location.city, Venue.location.state).all()
, but I got the following error: 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.