Code

Ticket #1717: content_type_model_cache.diff

File content_type_model_cache.diff, 1.3 KB (added by Dave St.Germain <dcs@…>, 8 years ago)

a simple cache for content types

Line 
1Index: django/contrib/contenttypes/models.py
2===================================================================
3--- django/contrib/contenttypes/models.py       (revision 4306)
4+++ django/contrib/contenttypes/models.py       (working copy)
5@@ -1,6 +1,7 @@
6 from django.db import models
7 from django.utils.translation import gettext_lazy as _
8 
9+CONTENT_TYPE_CACHE = {}
10 class ContentTypeManager(models.Manager):
11     def get_for_model(self, model):
12         """
13@@ -8,10 +9,15 @@
14         ContentType if necessary.
15         """
16         opts = model._meta
17-        # The str() is needed around opts.verbose_name because it's a
18-        # django.utils.functional.__proxy__ object.
19-        ct, created = self.model._default_manager.get_or_create(app_label=opts.app_label,
20-            model=opts.object_name.lower(), defaults={'name': str(opts.verbose_name)})
21+        key = (opts.app_label, opts.object_name.lower())
22+        try:
23+            ct = CONTENT_TYPE_CACHE[key]
24+        except KeyError:
25+            # The str() is needed around opts.verbose_name because it's a
26+            # django.utils.functional.__proxy__ object.
27+            ct, created = self.model._default_manager.get_or_create(app_label=key[0],
28+                model=key[1], defaults={'name': str(opts.verbose_name)})
29+            CONTENT_TYPE_CACHE[key] = ct
30         return ct
31 
32 class ContentType(models.Model):