One to many relationship flask

Viewed 217

I have class which represents stuff:

class Stuff(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    price = db.Column(db.Integer, nullable=False)
    name = db.Column(db.String(100), unique=True, nullable=False)
    logo = db.Column(db.Text)
    description = db.Column(db.Text)

    def __repr__(self):
        return '<Stuff %r>' % self.name

And have class which represents User:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    name = db.Column(db.String(80), unique=False, nullable=False)
    cart = db.Column(db.Text)

    def __repr__(self):
        return '<User %r>' % self.name

Here cart is json string like "["Stuff_id_1", "Stuff_id_2"]"
To add new item i just change this string
Example: i need to delete last item from cart("["Stuff_id_1", "Stuff_id_2"]"). To do that i just change string to "["Stuff_id_1"]" and edit cart column in User Model. I understand that my way of using cart column is dumb
How to make relationship one to many?

1 Answers

To make this relationship One-to-Many you would need to edit the Stuff class and add a foreign key to the User table.

class Stuff(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    price = db.Column(db.Integer, nullable=False)
    name = db.Column(db.String(100), unique=True, nullable=False)
    logo = db.Column(db.Text)
    description = db.Column(db.Text)
    user_id = db.Column(db.ForeignKey('name_of_users_table.id'))
    user = relationship('User', backref='user_stuffs')

    def __repr__(self):
        return '<Stuff %r>' % self.name

Now you can use the relationship like this:

user = User()
stuff = Stuff()

# Add to the relationship
user.user_stuffs.append(stuff)
db.session.commit()
Related