user8303487
user8303487

Reputation: 31

How to Update Entity with one to many relationship in flask-sqlachemy

I have two models, class Parents and class Child, I want to update the attributes of these classses, suppose, we have: parent_name = "P1", child_name = {"c1", "c2", "c3"},   After updating, we will have, parent_name = "P2", child_name = {"c1", "c2", "c3", "c4", "c5"

I already researched it, did not find the solution, give a suggestion

class Parent(db.Model):
    __tablename__ = 'parent'
    id = db.Column(db.Integer, primary_key=True)
    children = relationship("Child" backref='parent', passive_deletes=True)
    parent_name = db.Column(db.String(64))

class Child(Base):
    __tablename__ = 'child'
    id = db.Column(db.Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id', ondelete='CASCADE'))
   child_name = db.Column(db.String(64))

Upvotes: 0

Views: 2898

Answers (1)

Jesse Bakker
Jesse Bakker

Reputation: 2623

parent = session.query(Parent).filter(Parent.name='P1').one()
parent.parent_name = 'P2'
parent.children.extend([Child(child_name='c4'), Child(childe_name='c5')])
session.commit()

First you query the parent from the session. Then you edit it, where it will remain in the session, so that when you commit, the changes in the session get propagated to the database.

Upvotes: 2

Related Questions