【问题标题】:What is the proper way to insert an object with a foreign key in SQLAlchemy?在 SQLAlchemy 中插入具有外键的对象的正确方法是什么?
【发布时间】:2011-08-02 09:44:39
【问题描述】:

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

【问题讨论】:

    标签: python sqlalchemy pyramid


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多