Sometimes, we want to insert many-to-many data with Python Flask and SQLAlchemy.
In this article, we’ll look at how to insert many-to-many data with Python Flask and SQLAlchemy.
How to insert many-to-many data with Python Flask and SQLAlchemy?
To insert many-to-many data with Python Flask and SQLAlchemy, we can append the data with append.
For instance, we write
association_table = db.Table('association', db.Model.metadata,
db.Column('left_id', db.Integer, db.ForeignKey('left.id')),
db.Column('right_id', db.Integer, db.ForeignKey('right.id'))
)
class Parent(db.Model):
__tablename__ = 'left'
id = db.Column(db.Integer, primary_key=True)
children = db.relationship("Child",
secondary=association_table)
class Child(db.Model):
__tablename__ = 'right'
id = db.Column(db.Integer, primary_key=True)
p = Parent()
c = Child()
p.children.append(c)
db.session.add(p)
db.session.commit()
to create the association_table that creates a many to many relationship between Parent and Child.
Then we create a Parent and Child instance with
p = Parent()
c = Child()
Next, we create a link between p and c with
p.children.append(c)
Then we commit the operation with
db.session.add(p)
db.session.commit()
Conclusion
To insert many-to-many data with Python Flask and SQLAlchemy, we can append the data with append.