Commits

Gregory Petukhov committed 5183b3e

Add common.orm::generic_select_related

  • Participants
  • Parent commits d2322be

Comments (0)

Files changed (1)

File common/orm.py

+from collections import defaultdict
+
+from django.contrib.contenttypes.models import ContentType
+
 def iterate(qs, step=5000):
     """
     Reduce memory usage by splitting query into a number of queries using offset, limit
 
     for pk, rel_list in temp_map.iteritems():
         setattr(obj_map[pk], cache_field_name, rel_list)
+
+
+def generic_select_related(qs):
+    generics = defaultdict(set)
+    for item in qs:
+        generics[item.content_type_id].add(item.object_id)
+
+    content_types = ContentType.objects.in_bulk(generics.keys())
+
+    relations = {}
+    for ct, fk_list in generics.items():
+        ct_model = content_types[ct].model_class()
+        relations[ct] = ct_model.objects.in_bulk(list(fk_list))
+
+    for item in qs:
+        try:
+            setattr(item, '_content_object_cache', 
+                    relations[item.content_type_id][item.object_id])
+        except KeyError:
+            setattr(item, '_content_object_cache', None)