我想在AuthorComments和回复他的评论之间建立关系。
这是我的 models.py :
class AuthorComments(Base):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
name = db.Column(db.String(50))
email = db.Column(db.String(50), unique=True)
comment = db.Column(db.Text)
live = db.Column(db.Boolean)
comments = db.relationship('Reply', backref='reply', lazy='joined')
def __init__(self,author, name, email, comment, live=True):
self.author_id = author.id
self.name = name
self.email = email
self.comment = comment
self.live = live
class Reply(Base):
id = db.Column(db.Integer, primary_key=True)
reply_id = db.Column(db.Integer, db.ForeignKey('author.id'))
name = db.Column(db.String(50))
email = db.Column(db.String(50), unique=True)
comment = db.Column(db.Text)
live = db.Column(db.Boolean)
def __init__(self,author, name, email, comment, live=True):
self.reply_id = author.id
self.name = name
self.email = email
self.comment = comment
self.live = live
为什么我收到此错误: 的 sqlalchemy.exc.InvalidRequestError
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Could not determine join condition between parent/child tables on relationship AuthorComments.comments - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
答案 0 :(得分:2)
你的麻烦是SQLAlchemy不知道,对于子表(Reply
)的给定行,要选择父表(AuthorComments
)的哪一行!您需要在Reply
中定义一个引用其父AuthorComments
列的外键列。
Here是关于在SQLAlchemy中定义一对多关系的文档。
这样的事情:
class AuthorComments(Base):
__tablename__ = 'author_comment'
...
class Reply(Base):
...
author_comment_id = db.Column(db.Integer, db.ForeignKey('author_comment.id'))
...
author_comment = db.relationship(
'AuthorComments',
backref='replies',
lazy='joined'
)
将导致每个reply
获得与author_comment
的关系,如果不存在此类相等,则会some_reply.author_comment_id == some_author_comment.id
或None
。
backref
允许每个author_comment
相互与称为replies
的回复集合建立关系,满足上述条件。