diff options
Diffstat (limited to 'django/contrib/contenttypes/models.py')
-rw-r--r-- | django/contrib/contenttypes/models.py | 24 |
1 files changed, 20 insertions, 4 deletions
diff --git a/django/contrib/contenttypes/models.py b/django/contrib/contenttypes/models.py index a95748a9a1..0a5e68f37e 100644 --- a/django/contrib/contenttypes/models.py +++ b/django/contrib/contenttypes/models.py @@ -1,6 +1,7 @@ from django.db import models from django.utils.translation import gettext_lazy as _ +CONTENT_TYPE_CACHE = {} class ContentTypeManager(models.Manager): def get_for_model(self, model): """ @@ -8,11 +9,26 @@ class ContentTypeManager(models.Manager): ContentType if necessary. """ opts = model._meta - # The str() is needed around opts.verbose_name because it's a - # django.utils.functional.__proxy__ object. - ct, created = self.model._default_manager.get_or_create(app_label=opts.app_label, - model=opts.object_name.lower(), defaults={'name': str(opts.verbose_name)}) + key = (opts.app_label, opts.object_name.lower()) + try: + ct = CONTENT_TYPE_CACHE[key] + except KeyError: + # The str() is needed around opts.verbose_name because it's a + # django.utils.functional.__proxy__ object. + ct, created = self.model._default_manager.get_or_create(app_label=key[0], + model=key[1], defaults={'name': str(opts.verbose_name)}) + CONTENT_TYPE_CACHE[key] = ct return ct + + def clear_cache(self): + """ + Clear out the content-type cache. This needs to happen during database + flushes to prevent caching of "stale" content type IDs (see + django.contrib.contenttypes.management.create_contenttypes for where + this gets called). + """ + global CONTENT_TYPE_CACHE + CONTENT_TYPE_CACHE = {} class ContentType(models.Model): name = models.CharField(maxlength=100) |