我发现你可以在关系中使用集合来改变返回值的类型,特别是我对字典感兴趣。 文档举例:如何从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)
它的工作原理。不过,我希望如果不止有一个同名的关键字,它会创建列表值。但它只将最后一个值放在唯一键名下。
下面是一个例子:
| Note table |
|---------------------|------------------|
| id | keyword |
|---------------------|------------------|
| 1 | foo |
|---------------------|------------------|
| 2 | foo |
|---------------------|------------------|
| 3 | bar |
|---------------------|------------------|
| 4 | bar |
|---------------------|------------------|
item.notes
将返回这样的事情:
{'foo': <project.models.note.Note at 0x7fc6840fadd2>,
'bar': <project.models.note.Note at 0x7fc6840fadd4>}
其中foo和酒吧对象的ID分别为2和4。
什么我要找的是让这样的事情:
{'foo': [<project.models.note.Note at 0x7fc6840fadd1,
<project.models.note.Note at 0x7fc6840fadd2>],
'bar': [<project.models.note.Note at 0x7fc6840fadd3>,
<project.models.note.Note at 0x7fc6840fadd4>]}
是否有可能从SQLAlchemy的关系得到清单字典?
请解决您的压痕,给编辑的输入输出例子 –
:添加了一个例子,固定缩进 –