Best practice for retrieving and working with ContentTypes in Django views

1.5k views Asked by At

What's the more efficient way of retrieving identical Django ContentTypes in different views in one views.py?

a) Retrieving types in each view separately, like so:

from django.contrib.contenttypes.models import ContentType

def my_view1(request):
    t1 = ContentType.objects.get_for_model(my_model1)
    t2 = ContentType.objects.get_for_model(my_model2)
    # ... work with t1 and t2


def my_view2(request):
    t1 = ContentType.objects.get_for_model(my_model1)
    t2 = ContentType.objects.get_for_model(my_model2)
    # ... work with t1 and t2

or b) Retrieving the used types once as constants at the beginning of views.py, like so:

from django.contrib.contenttypes.models import ContentType

T1 = ContentType.objects.get_for_model(my_model1)
T2 = ContentType.objects.get_for_model(my_model2)

def my_view1(request):
    # ... work with T1 and T2


def my_view2(request):
    # ... work with T1 and T2

The ContentTypes database table is really small, however, Django still needs to make a connection for each query. So my guess is, b) is therefore faster ... ?!

1

There are 1 answers

2
Alex Emelin On BEST ANSWER

From comments line to get_for_model (source code):

Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don't hit the database.

So the result is cached and you can retrieve types separately in each view.

But consider a possibility of writing a single function or model method instead of duplicating code in views.