使用OrderedDict进行SQLAlchemy关系()?

时间:2016-10-04 16:14:54

标签: python python-3.x sqlalchemy

是否可以告诉SQLAlchemy将OrderedDict用于relationship存储?我只熟悉attribute_mapped_collection,但那是无序的。

1 个答案:

答案 0 :(得分:3)

文档中有example个:

from sqlalchemy.util import OrderedDict
from sqlalchemy.orm.collections import MappedCollection

class NodeMap(OrderedDict, MappedCollection):
    """Holds 'Node' objects, keyed by the 'name' attribute with insert order maintained."""

    def __init__(self, *args, **kw):
        MappedCollection.__init__(self, keyfunc=lambda node: node.name)
        OrderedDict.__init__(self, *args, **kw)

用法很简单:

foo = relationship(..., collection_class=NodeMap)