Python
06 Feb 2009 HTML Text
 
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def load_generic_related(qs, *args):
    """
    Do in 1 + M(number of content types) quries the loading
    of related object which linked via GenericForeignKey
    """

    items = qs.select_related('content_type')

    model_map = {}
    item_map = {}

    for item in items:
        model_map.setdefault(item.content_type, {})\
            .setdefault(item.object_id, []).append(item.id)
        item_map[item.id] = item

    for ctype, ids in model_map.items():
        cobjects = ctype.model_class().objects.select_related(*args)\
            .filter(id__in=ids.keys())
        for obj in cobjects:
            for id in ids[obj.id]:
                item_map[id].content_object = obj

    return items