我的Flask应用程序中有一个Artist-hasMany-Suggestion关系(用Flask-SQLAlchemy实现)。
我的艺术家课程如下:
class Artist(db.Model):
__tablename__ = 'artists'
suggestions = db.relationship('Suggestion', backref='artist')
我的Suggestion类看起来像:
class Suggestion(db.Model):
__tablename__ = 'suggestions'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'))
def __repr__(self):
return '<Suggestion %r>' % (self.artist.name,)
显然,问题是没有为Suggestion模型定义self.artist
。我能做些什么来实现这个目标?
答案 0 :(得分:2)
Actualy问题是Suggestion
不一定有关联Artist
。它打破了一切。因此,请检查self.artist
None
或强制它NULL
。
我的测试代码:
class Artist(db.Model):
__tablename__ = 'artists'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
suggestions = db.relationship('Suggestion', backref='artist')
class Suggestion(db.Model):
__tablename__ = 'suggestions'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'))
def __repr__(self):
return '<Suggestion %r>' % (self.artist.name,)
和IPython会议:
In [1]: from sqlalch import db, Artist, Suggestion
In [2]: Artist.query.all()
Out[2]: [<sqlalch.Artist at 0x3559490>]
In [3]: Suggestion.query.all()
Out[3]: [<Suggestion u'Hey You!'>]
In [4]: Suggestion.query.all()[0].artist
Out[4]: <sqlalch.Artist at 0x3559490>