When using SQLAlchemy, what is the ideal way to insert an object into a table with a column that is a foreign key and then commit it? Is there anything wrong with inserting objects with a foreign in the code below?
def retrieve_objects():
session = DBSession()
return session.query(SomeClass).all()
def insert_objects():
session = DBSession()
for obj in retrieve_objects():
another_obj = AnotherClass(somefield=0)
obj.someforeignkey = another_obj
session.add(obj)
session.flush()
transaction.commit()
session.close()
return None
If you aren't using SQLAlchemy relationships on your ORM objects you have to manually deal with foreign keys. This means you have to create the parent object first, get its primary key back from the database, and use that key in the child's foreign key:
def retrieve_objects():
session = DBSession()
return session.query(SomeClass).all()
def insert_objects():
session = DBSession()
for obj in retrieve_objects():
another_obj = AnotherClass(somefield=0)
session.add(another_obj)
session.flush() # generates the pkey for 'another_obj'
obj.someforeignkey = another_obj.id # where id is the pkey
session.add(obj)
transaction.commit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With