简体   繁体   English

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

[英]How to get dict of lists from relationship in sqlalchemy?

I've found out that you can use collections in relationship in order to change the type of return value, specifically I was interested in dictionaries.我发现你可以在关系中使用集合来改变返回值的类型,特别是我对字典感兴趣。 Documentation gives an example :文档给出了一个例子

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)

And it works.它有效。 However I was hoping that it will make list values if there are more than just one key with the same name.但是,我希望如果同名的键不止一个,它会生成列表值。 But it only puts the last value under unique key name.但它只将最后一个值放在唯一键名下。

Here is an example:下面是一个例子:

|               Note table               |
|---------------------|------------------|
|          id         |      keyword     |
|---------------------|------------------|
|          1          |        foo       |
|---------------------|------------------|
|          2          |        foo       |
|---------------------|------------------|
|          3          |        bar       |
|---------------------|------------------|
|          4          |        bar       |
|---------------------|------------------|

item.notes will return something like this: item.notes将返回如下内容:

{'foo': <project.models.note.Note at 0x7fc6840fadd2>,
 'bar': <project.models.note.Note at 0x7fc6840fadd4>}

Where ids of foo and bar objects are 2 and 4 respectively.其中 foo 和 bar 对象的 id 分别为 2 和 4。

What I'm looking for is to get something like this:我正在寻找的是得到这样的东西:

{'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>]}

Is it possible to get dict of lists from relationship in sqlalchemy?是否可以从 sqlalchemy 中的关系中获取列表的字典?

So, it turns out you can simply inherit MappedCollection and do whatever you like in setitem there.所以,事实证明你可以简单地继承 MappedCollection 并在那里的 setitem 中做任何你喜欢的事情

from sqlalchemy.orm.collections import (MappedCollection,
                                        _SerializableAttrGetter,
                                        collection,
                                        _instrument_class)

#This will ensure that the MappedCollection has been properly 
#initialized with custom __setitem__() and __delitem__() methods 
#before used in a custom subclass
_instrument_class(MappedCollection)


class DictOfListsCollection(MappedCollection):

    @collection.internally_instrumented
    def __setitem__(self, key, value, _sa_initiator=None):
        if not super(DictOfListsCollection, self).get(key):
            super(DictOfListsCollection, self).__setitem__(key, [], _sa_initiator)
        super(DictOfListsCollection, self).__getitem__(key).append(value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM