Ticket #1717: content_type_model_cache.diff

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

a simple cache for content types

  • django/contrib/contenttypes/models.py

     
    11from django.db import models
    22from django.utils.translation import gettext_lazy as _
    33
     4CONTENT_TYPE_CACHE = {}
    45class ContentTypeManager(models.Manager):
    56    def get_for_model(self, model):
    67        """
     
    89        ContentType if necessary.
    910        """
    1011        opts = model._meta
    11         # The str() is needed around opts.verbose_name because it's a
    12         # django.utils.functional.__proxy__ object.
    13         ct, created = self.model._default_manager.get_or_create(app_label=opts.app_label,
    14             model=opts.object_name.lower(), defaults={'name': str(opts.verbose_name)})
     12        key = (opts.app_label, opts.object_name.lower())
     13        try:
     14            ct = CONTENT_TYPE_CACHE[key]
     15        except KeyError:
     16            # The str() is needed around opts.verbose_name because it's a
     17            # django.utils.functional.__proxy__ object.
     18            ct, created = self.model._default_manager.get_or_create(app_label=key[0],
     19                model=key[1], defaults={'name': str(opts.verbose_name)})
     20            CONTENT_TYPE_CACHE[key] = ct
    1521        return ct
    1622
    1723class ContentType(models.Model):
Back to Top