Its absolutely usual case but I can not find easy solution. Simple example :
I have two related tables :
class Parent(db.Model):
__tablename___ = 'parent_table'
id = db.Column(db.Integer, primary_key=True)
...
children = db.relationship("Children", secondary=parent_children , uselist=True)
class Children(db.Model):
__tablename___ = 'children_table'
id = db.Column(db.Integer, primary_key=True)
...
parent_children = db.Table(
'parent_children_table',
db.Column('parent_id', db.Integer, ForeignKey('parent_table.id')),
db.Column('children_id', db.Integer, ForeignKey('children_table.id'))
)
Ok. It is absolutly easy many to many scheme. Next step we insert data into parent_table with linked children_table data.
children_list = []
children = Children(
id=1
)
children_list.apppend(children)
parent = Parent(
id=1
)
parent.children.extend(children_list)
db.session.add(parent)
db.session.commit()
So we have two records in each tables and one linked record in 'parent_children_table'. Next step we continue insert data:
children_list = []
children = Children(
id=1
)
children_list.apppend(children)
parent = Parent(
id=2
)
parent.children.extend(children_list)
db.session.add(parent)
db.session.commit()
Here we have Children object with same id we already have in table. What is my goal? I want update this row or just skip but I have error 'Key"(id)=(1)" already exists'. How I can say ORM to update row if it is already exists? I just want to have two Parent rows linked with the same Children.
Thanks for help!