0

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!

Ilya Demidov
  • 3,275
  • 2
  • 26
  • 38
  • Related: https://stackoverflow.com/a/69225139/2144390 – Gord Thompson Mar 29 '23 at 14:02
  • You probably want `merge` - or for bulk upserts something like the answer here: https://stackoverflow.com/questions/25955200/sqlalchemy-performing-a-bulk-upsert-if-exists-update-else-insert-in-postgr/26018934#26018934 – match Mar 29 '23 at 14:05

0 Answers0