gpt4 book ai didi

python - SqlALchemy 外键链接两个表时出错

转载 作者:行者123 更新时间:2023-12-01 09:28:08 26 4
gpt4 key购买 nike

我无法将两个表与“帖子”和“评论”链接起来,因此评论仅显示在创建评论的特定帖子上。

通过链接帖子和用户,我使用 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

最佳答案

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

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')

关于python - SqlALchemy 外键链接两个表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com