user9665527
user9665527

Reputation:

SqlALchemy ForeignKey error linking two tables

I have trouble linking two tables with 'Posts' and 'Comments' so comments are only displayed on particular post, where they have been created.

With linking post and user I used current_user.id to make link between tables, but using ForeignKey gaves me always error:

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

Below is my code:

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

Upvotes: 1

Views: 71

Answers (1)

mohamad khajezade
mohamad khajezade

Reputation: 181

In your relationship, you have to change the name of the tables.

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

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

I have corrected your code:

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

Upvotes: 1

Related Questions