两个表之间的关系,SQLAlchemy

时间:2016-08-08 22:20:25

标签: python sqlalchemy flask-sqlalchemy rdbms

我想在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.

1 个答案:

答案 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.idNone

backref允许每个author_comment相互与称为replies的回复集合建立关系,满足上述条件。