Best practice for retrieving and working with ContentTypes in Django views
Asked Answered
A

1

6

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 ... ?!

Asafetida answered 6/8, 2013 at 10:51 Comment(0)
K
8

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.

Karate answered 6/8, 2013 at 11:41 Comment(2)
Assuming the cache is retained outside the views, that would be perfect. So the question is: is this cache global or is it - like normal Django querysets - limited to the runtime of one view?Asafetida
It's like your b) option from question. Cache will be shared between any request using the same worker/server process. For example, if you run Django under Gunicorn and start 9 workers - then each worker will have its own ContentType cache.Karate

© 2022 - 2024 — McMap. All rights reserved.