小编Rhd*_*hdr的帖子

如何从sqlalchemy中的关系中获取列表的字典?

我发现你可以在关系中使用集合来改变返回值的类型,特别是我对字典感兴趣。文档给出了一个例子

class Item(Base):
    __tablename__ = 'item'
    id = Column(Integer, primary_key=True)
    notes = relationship("Note",
                         collection_class=attribute_mapped_collection('keyword'),
                         cascade="all, delete-orphan")

class Note(Base):
    __tablename__ = 'note'
    id = Column(Integer, primary_key=True)
    item_id = Column(Integer, ForeignKey('item.id'), nullable=False)
    keyword = Column(String)
    text = Column(String)
Run Code Online (Sandbox Code Playgroud)

它有效。但是,我希望如果同名的键不止一个,它会生成列表值。但它只将最后一个值放在唯一键名下。

下面是一个例子:

|               Note table               |
|---------------------|------------------|
|          id         |      keyword     |
|---------------------|------------------|
|          1          |        foo       |
|---------------------|------------------|
|          2          |        foo       |
|---------------------|------------------|
|          3          |        bar       |
|---------------------|------------------|
|          4          |        bar       |
|---------------------|------------------|
Run Code Online (Sandbox Code Playgroud)

item.notes 将返回如下内容:

{'foo': <project.models.note.Note at …
Run Code Online (Sandbox Code Playgroud)

python dictionary sqlalchemy relationship

6
推荐指数
1
解决办法
2037
查看次数

标签 统计

dictionary ×1

python ×1

relationship ×1

sqlalchemy ×1