Best practice for retrieving and working with ContentTypes in Django views
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 ... ?!
No comments:
Post a Comment