What is the proper way to insert an object with a foreign key in SQLAlchemy?

北城以北 提交于 2019-12-10 02:48:13

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/5610563/what-is-the-proper-way-to-insert-an-object-with-a-foreign-key-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!