gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:21:51 25 4
gpt4 key购买 nike

如何在构造函数中添加有关系的对象?评估构造函数时,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地址中,您就完成了:

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 的一部分模式。

关于python - 如何在 SQLAlchemy 模型的构造函数中通过关系存储数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882616/

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