简体   繁体   中英

Querying a table from another table using SQLAlchemy

I am new to programming and learning about relational databases using SQLAlchemy, Python and 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):

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' . 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))    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM