gpt4 book ai didi

python - Flask SQLAlchemy 关联表 : error creating backref

转载 作者:行者123 更新时间:2023-12-01 06:30:39 25 4
gpt4 key购买 nike

我有一个 Artist 模型和一个 Venue 模型,它们之间存在由 Show 模型促进的多对多关系(演出表明音乐会的艺术家、地点和日期)。

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

我想查询所有即将举行的演出的 field 名称、艺术家姓名和日期,因此请记住以下内容...

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

...这样我就可以访问即将到来的节目[0].Venue.name、即将到来的_节目[0].Artist.name 和即将到来的_节目[0].start_time。

但是该查询返回以下内容:

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

感觉我已经很接近了,但缺少一些基本的东西!

最佳答案

已解决。我对代码进行了以下更改,现在它可以工作了。最后相当简单,我只需确保关系名称是唯一的:-\

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

关于python - Flask SQLAlchemy 关联表 : error creating backref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59927780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com