Inserting A Child Object With A Parent When The Parent Already Exists With SQLAlchemy
I would like to insert an child object (see class definitions below) which has a relationship with a parent object which may or may not already exists in the database, and then get
Solution 1:
Instead of arbitrarily creating parent = Parent(id = 1) you should check if it already exists:
# retrieve parent from database …
parent1 = session.get(Parent, 1)
if not parent1:
# … and create if not found
session.add(parent1 := Parent(id=1, name="Homer"))
Post a Comment for "Inserting A Child Object With A Parent When The Parent Already Exists With SQLAlchemy"