如何在SQLAlchemy模型的构造函数中通过关系存储数据?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在SQLAlchemy模型的构造函数中通过关系存储数据?相关的知识,希望对你有一定的参考价值。

如何在构造函数中添加具有关系的对象?在评估构造函数时,id尚未就绪。在更简单的情况下,可以提供预先计算的列表。在下面的例子中,我试图说有一个complex_cls_method,在某种程度上它更像黑盒子。

from sqlalchemy import create_engine, MetaData, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker

DB_URL = "mysql://user:password@localhost/exampledb?charset=utf8"

engine = create_engine(DB_URL, encoding='utf-8', convert_unicode=True, pool_recycle=3600, pool_size=10)
session = sessionmaker(autocommit=False, autoflush=False, bind=engine)()

Model = declarative_base()


class User(Model):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    simple = Column(String(255))
    main_address = Column(String(255))
    addresses = relationship("Address",
                             cascade="all, delete-orphan")

    def __init__(self, addresses, simple):
        self.simple = simple
        self.main_address = addresses[0]
        return  # because the following does not work
        self.addresses = Address.complex_cls_method(
            user_id_=self.id,  # <-- this does not work of course
            key_="address",
            value_=addresses
        )


class Address(Model):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    keyword = Column(String(255))
    value = Column(String(255))
    user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
    parent_id = Column(Integer, ForeignKey('address.id'), nullable=True)

    @classmethod
    def complex_cls_method(cls, user_id_, key_, value_):
        main = Address(keyword=key_, value="", user_id=user_id_, parent_id=None)
        session.add_all([main])
        session.flush()
        addrs = [Address(keyword=key_, value=item, user_id=user_id_, parent_id=main.id) for item in value_]
        session.add_all(addrs)
        return [main] + addrs


if __name__ == "__main__":
    # Model.metadata.create_all(engine)
    user = User([u"address1", u"address2"], "simple")
    session.add(user)
    session.flush()

    # as it can't be done in constructor, these additional statements needed 

    user.addresses = Address.complex_cls_method(
        user_id_=user.id,
        key_="address",
        value_=[u"address1", u"address2"]
    )
    session.commit()

问题是,使用User的构造函数是否存在语法上优雅(和技术上合理)的方法,或者在session.flush之后调用User类的单独方法更安全,以便将所需的对象添加到关系中(如示例代码中所示) )?

完全放弃构造函数仍然是可能的,但是由于产生的签名更改而不太可取的选项将需要显着的重构。

答案

您可以让SQLAlchemy处理持久化对象图,而不是手动刷新和设置ID等。你只需要在adjacency list relationship再多一个Address就可以了:

class User(Model):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    simple = Column(String(255))
    main_address = Column(String(255))
    addresses = relationship("Address",
                             cascade="all, delete-orphan")

    def __init__(self, addresses, simple):
        self.simple = simple
        self.main_address = addresses[0]
        self.addresses = Address.complex_cls_method(
            key="address",
            values=addresses
        )


class Address(Model):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    keyword = Column(String(255))
    value = Column(String(255))
    user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
    parent_id = Column(Integer, ForeignKey('address.id'), nullable=True)
    # For handling parent/child relationships in factory method
    parent = relationship("Address", remote_side=[id])

    @classmethod
    def complex_cls_method(cls, key, values):
        main = cls(keyword=key, value="")
        addrs = [cls(keyword=key, value=item, parent=main) for item in values]
        return [main] + addrs    

if __name__ == "__main__":
    user = User([u"address1", u"address2"], "simple")
    session.add(user)
    session.commit()
    print(user.addresses)

请注意,没有手动刷新等.SQLAlchemy会根据对象关系自动计算出所需的插入顺序,以便可以遵循行之间的依赖关系。这是Unit of Work模式的一部分。

以上是关于如何在SQLAlchemy模型的构造函数中通过关系存储数据?的主要内容,如果未能解决你的问题,请参考以下文章

SQLAlchemy学习-4.一对一关系

SQLAlchemy中的 backref具体用途

为啥复制构造函数应该在 C++ 中通过引用来接受它的参数?

在 C++ 中通过构造函数复制类

为啥我们需要一个默认构造函数来在 C++ 中通过引用传递一个对象?

在 Rails 中通过其 belongs_to 关系查询记录