[英]Querying a table from another table using SQLAlchemy
I am new to programming and learning about relational databases using SQLAlchemy, Python and Flask.我是使用 SQLAlchemy、Python 和 Flask 来编程和学习关系数据库的新手。
I want to know if it's possible and if so, how to get information referencing one table which is connected to multiple others.我想知道它是否可能,如果可能,如何获取引用一个连接到多个其他表的信息。 For example, I have the below table connected to another (using SQLAlchemy):
例如,我将下表连接到另一个(使用 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
? 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'
. 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'
。 Is there a better way to do this?有一个更好的方法吗?
Maybe you can try this也许你可以试试这个
vlocations = []
for venue in Venue.query.all():
vlocations.extened(venue.location)
vlocations = list(set(vlocations))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.