【发布时间】:2018-05-06 19:12:30
【问题描述】:
我无法使用“帖子”和“评论”链接两个表格,因此 cmets 仅显示在创建它们的特定帖子上。
通过链接帖子和用户,我使用 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
【问题讨论】:
标签: python flask sqlalchemy