用SQLAlchemy中的外键插入对象的正确方法是什么?

问题描述:

当使用SQLAlchemy时,将对象插入到一个列是外键的表中然后提交它的理想方法是什么?在下面的代码中插入具有外部对象的对象有什么问题吗?用SQLAlchemy中的外键插入对象的正确方法是什么?

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 
+2

你为什么不申报的外键关系作为其一部分的模型和一切都会自动为你完成?这就是为什么我们有Sqlalchemy。如果你不使用它的功能,那么根本不要使用Sqlalchemy。 – 2011-04-10 08:30:48

如果您不在ORM对象上使用SQLAlchemy关系,则必须手动处理外键。这意味着你必须首先创建父对象,获取其主键从数据库返回的,并使用该密钥在孩子的外键:

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()