What is the proper way to insert an object with a foreign key in SQLAlchemy?
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()
精彩评论