gpt4 book ai didi

python - 在 SQLAlchemy 中插入带有外键的对象的正确方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 21:47:42 26 4
gpt4 key购买 nike

当使用 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

最佳答案

如果您没有在 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()

关于python - 在 SQLAlchemy 中插入带有外键的对象的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5610563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com