gpt4 book ai didi

python - 如何在 sqlalchemy 中使用 Dict[str, str] 作为关系属性

转载 作者:行者123 更新时间:2023-12-05 05:15:16 26 4
gpt4 key购买 nike

假设我有一个模型,从概念上讲,它应该只是父级从一种简单类型到另一种简单类型的字典。我已经尝试实现自定义集合类,但它似乎不是正确的方法,因为自定义集合在将其添加到集合时应采用 L1 类型的内容作为参数。但是我想要的接口(interface)是 Root(children={'a': 'a'})

class L1(Base):

__tablename__ = 'l1s'

id = sa.Column(sa.Integer, primary_key=True)
parent_id = sa.Column(sa.Integer, sa.ForeignKey('roots.id'))
name = sa.Column(sa.String, unique=True)
value = sa.Column(sa.String)





class Root(Base):

__tablename__ = 'roots'

id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String, unique=True)
children = relationship('L1', backref='parent', collection_class=partial(AsSimpleDict, L1, 'name', 'value'))

最佳答案

我认为您可能正在寻找的是 collection_class 关系和 association_proxy 的组合。

class Parent(declarative.Base):
__tablename__ = 'parent'

id = Column("parent_id", Integer, primary_key=True)

_config = relationship("Config",
collection_class=attribute_mapped_collection('key'),
cascade="all, delete-orphan")
config = association_proxy('_config', 'value',
creator=lambda k, v: Config(key=k, value=v))

class Config(declarative.Base):
__tablename__ = 'config'

id = Column("config_id", Integer, primary_key=True)

parent_id = Column(Integer, ForeignKey('parent.parent_id'))
playlist = relationship("Parent", back_populates="_config")
key = Column(String)
value = Column(String)

我的理解是,在这个例子中,_config 实际上是一个 key -> Config object 字典,并且关联代理接受它并将它呈现为一个 key -> value 字典。最后,creator 函数将 parent.config[key] = value 赋值转换为在幕后创建 Config 对象。

关于python - 如何在 sqlalchemy 中使用 Dict[str, str] 作为关系属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51748865/

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