是否可以告诉SQLAlchemy将OrderedDict
用于relationship
存储?我只熟悉attribute_mapped_collection
,但那是无序的。
答案 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)