在 SQLAlchemy 中插入带有外键的对象的正确方法是什么? [英] What is the proper way to insert an object with a foreign key in SQLAlchemy?

查看:50
本文介绍了在 SQLAlchemy 中插入带有外键的对象的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

如果您没有在 ORM 对象上使用 SQLAlchemy 关系,则必须手动处理外键.这意味着您必须首先创建父对象,从数据库中取回其主键,然后在子对象的外键中使用该键:

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

这篇关于在 SQLAlchemy 中插入带有外键的对象的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆