there's two variations here. One, which is definitely the quickest, is just to use a @property that re-evaulates library.books as a dict:
@property
def books_by_id(self):
return dict((
book.id, book) for book in self.books)
the other, the more "integrated" approach, is to use a collection_class that's mostly a dict but just yields the values instead of the keys when iterated. It might be nice if attribute_mapped_collection provided a simple argument to pass in a "dict" subclass but apparently it doesn't have this yet, so just subclass MappedCollection:
class IterateValuesDict(MappedCollection):
def __iter__(self):
return iter(self.values())
collection_cls = lambda: IterateValuesDict(keyfunc=lambda obj:
obj.id)
class Library(Base):
# ...
books = relationship(Book, collection_cls=collection_cls)
Thanks,
--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To view this discussion on the web visit https://groups.google.com/d/msg/sqlalchemy/-/mUIFlVguh34J.
To post to this group, send email to sqlal...@googlegroups.com.
To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.