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

Mar*_*lin 9 python sqlalchemy pyramid

使用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
Run Code Online (Sandbox Code Playgroud)

Mic*_*kel 6

如果您未在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()
Run Code Online (Sandbox Code Playgroud)