【问题标题】:SqlALchemy ForeignKey error linking two tablesSqlALchemy ForeignKey 错误链接两个表
【发布时间】: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


    【解决方案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')
    

    【讨论】:

    • 谢谢,db 正在工作,只是没有绑定外键和创建 post_id
    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 2011-11-25
    • 2020-10-24
    • 2021-08-16
    • 1970-01-01
    • 2021-05-15
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多