Answer a question

I have a Artist model, and a Venue model, and they have a many-to-many relationship facilitated by the Show model (the shows indicate the artist, venue and date of the concert).

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

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
shows = db.relationship('Show', backref='venue', lazy=True)   

class Artist(db.Model):
__tablename__ = 'Artist'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
shows = db.relationship('Show', backref='artist', lazy=True)

class Show(db.Model):
  __tablename__ = 'Show'

  id = db.Column(db.Integer, primary_key=True)
  venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)
  artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)      
  start_time = db.Column(db.DateTime, nullable=False)    
  venue = db.relationship('Venue', back_populates='venue')
  artist = db.relationship('Artist', back_populates='artist')

I'd like to have a query to get the venue name, artist name, and date of all upcoming shows so had in mind the following...

upcoming_shows = Show.query.filter_by(show.start_time >= datetime.now()).all()

...so that I can then access for example, upcoming_shows[0].Venue.name, upcoming_shows[0].Artist.name and upcoming_shows[0].start_time.

That query however returns the following:

sqlalchemy.exc.ArgumentError: Error creating backref 'venue' on relationship 'Venue.shows': property of that name exists on mapper 'mapped class Show->Show'

Feel like I'm close but missing something fundamental!

Answers

Solved. I made the changes below to the code and it works now. It was rather straight-forward in the end, I simply had to ensure that the relationship names were unique :-\

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

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
venue_shows = db.relationship('Show', back_populates='venue', lazy=True)   

class Artist(db.Model):
__tablename__ = 'Artist'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
artist_shows = db.relationship('Show', back_populates='artist', lazy=True)

class Show(db.Model):
  __tablename__ = 'Show'

  id = db.Column(db.Integer, primary_key=True)
  venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)
  artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)    

  start_time = db.Column(db.DateTime, nullable=False)

  venue = db.relationship('Venue', back_populates='venue_shows')
  artist = db.relationship('Artist', back_populates='venue_artist')
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐