Bex T.
Bex T.

Reputation: 1786

Foreign keys, relationship between models in sqlalchemy flask

I have these two models:

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    __table_args__ = (
        PrimaryKeyConstraint('id',),
    )

    id       = db.Column(db.Integer, primarky_key=True)
    username = db.Column(db.String, unique=True, nullable=False)
    email    = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)


class Review(db.Model):
    __tablename__ = 'reviews'
    __table_args__ = (
        PrimaryKeyConstraint('id', ),
    )
    id        = db.Column(db.Integer, primary_key=True)
    content   = db.Column(db.Text, nullable=False)

I wanted to create a relationship between these two tables so that when a user writes a review it should go to Review model and it has a relation with user_id in Users model. I have tried lots of answers but they are returning different kinds of errors I am confused, can anybody help?

Upvotes: 2

Views: 2586

Answers (2)

Angelo Mendes
Angelo Mendes

Reputation: 978

Try this:

user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship(User, backref='user_reviews', lazy=True)

And read the documentation.

Upvotes: 0

tjholub
tjholub

Reputation: 714

You can use db.relationship to create a one-to-many relationship between users and reviews.

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    __table_args__ = (
        PrimaryKeyConstraint('id',),
    )

    id       = db.Column(db.Integer, primarky_key=True)
    username = db.Column(db.String, unique=True, nullable=False)
    email    = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)
    reviews = db.relationship('Review', backref='user', cascade='all, delete, delete-orphan')


class Review(db.Model):
    __tablename__ = 'reviews'
    __table_args__ = (
        PrimaryKeyConstraint('id', ),
    )
    id        = db.Column(db.Integer, primary_key=True)
    content   = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)

This would allow for user.reviews and review.user

Upvotes: 2

Related Questions