连接两个表时出现SqlALchemy ForeignKey错误

时间:2018-05-06 10:39:41

标签: python flask sqlalchemy

我无法将两个表格与“帖子”相关联。和#39;评论'因此评论仅显示在已创建的特定帖子上。

使用链接帖子和用户我使用current_user.id在表之间建立链接,但是使用ForeignKey会给我总是错误:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Post.post_rel - there are no foreign keys linking these tables

以下是我的代码:

class Post(db.Model):

__tablename__ = 'post'

id = db.Column(Integer, primary_key=True)
title = db.Column(String(50))
subtitle = db.Column(String(50))
author = db.Column(String(20))
date_posted = db.Column(DateTime)
content = db.Column(Text)
post_rel = relationship('Post', back_populates='comment_rel', foreign_keys='[Comment.post_id]')

def get_comments(self):
    return Comments.query.filter_by(post_id=post.id).order_by(Comments.timestamp.desc())

def __repr__(self):
    return '<Post %r>' % (self.body)

class Comment(db.Model):

__tablename__ = 'comment'

id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(140))
author = db.Column(db.String(32))
timestamp = db.Column(db.DateTime(), default=datetime.utcnow, index=True)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
comment_rel = relationship('Comment', uselist=False, back_populates='post_rel')

def __init__(self, text, author, timestamp):
    """"""
    self.text = text
    self.author = author
    self.timestamp = timestamp

def __repr__(self):
    return '<Post %r>' % (self.body)

def show(self):
    return self.author + '\n' + self.text

1 个答案:

答案 0 :(得分:1)

在您的关系中,您必须更改表的名称。

post_rel = relationship('Comment', back_populates='comment_rel', 
foreign_keys='[Comment.post_id]')

comment_rel = relationship('Post', uselist=False, 
back_populates='post_rel')

我已更正您的代码:

BaseModel = declarative_base()

class Post(BaseModel):

    __tablename__ = 'post'

    id = Column(Integer, primary_key=True)
    title = Column(String(50))
    subtitle = Column(String(50))
    author = Column(String(20))
    post_rel = relationship('Comment', back_populates='comment_rel', foreign_keys='[Comment.post_id]')



class Comment(BaseModel):

    __tablename__ = 'comment'

    id = Column(Integer, primary_key=True)
    text = Column(String(140))
    author = Column(String(32))
    comment_rel = relationship('Post', uselist=False, back_populates='post_rel')