def attach_tags(objs): """ Fetch tags from `objs` in one query and then attach them to a property on each instance. Assumes every instance in `objs` uses the same model. """ if objs: obj_dict = {obj.id: obj for obj in objs} m2m_name = Tag._get_m2m_name(objs[0]) field_name = getattr(objs[0], m2m_name).query_field_name qs = (Tag.objects.not_blocked() .filter(**{'%s__in' % field_name: obj_dict.keys()}) .values_list('%s__id' % field_name, 'tag_text')) for obj, tags in sorted_groupby(qs, lambda x: x[0]): setattr(obj_dict[obj], '%s_list' % m2m_name, [t[1] for t in tags])
def rollup(xs): groups = sorted_groupby(xs, 'version_id') return dict((k, list(vs)) for k, vs in groups)