Skip to content

Commit

Permalink
Fixed #1717: ContentType.objects.get_for_manager() is now cached for …
Browse files Browse the repository at this point in the history
…a small performance gain when dealing with content-types regularly. Thanks, Dave St.Germain.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@4307 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
jacobian committed Jan 12, 2007
1 parent 73d6274 commit b118b28
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions django/contrib/contenttypes/models.py
@@ -1,17 +1,23 @@
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):
"""
Returns the ContentType object for the given model, creating the
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

class ContentType(models.Model):
Expand Down

0 comments on commit b118b28

Please sign in to comment.