Reputation: 31
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
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