def prefetch(session, discussion_id): from assembl.lib.sqla import class_registry from assembl.models import DiscussionBoundBase for name, cls in class_registry.items(): if issubclass(cls, DiscussionBoundBase) and not isabstract(cls): mapper = class_mapper(cls) undefers = [undefer(attr.key) for attr in mapper.iterate_properties if getattr(attr, 'deferred', False)] conditions = cls.get_discussion_conditions(discussion_id) session.query(with_polymorphic(cls, "*")).filter( and_(*conditions)).options(*undefers).all()