django-planet
March 23, 2023

Django: Avoid database queries in template context processors

published by Adam Johnson
in blog Adam Johnson
original entry Django: Avoid database queries in template context processors

Django’s template engine allows you to augment template contexts with context processors. These are functions that take the current request and return a dictionary to be merged into the context:

from example.models import HotDog
from example.models import HotDogState


def hot_dog_stats(request):
    return {
        "hot_dogs_eaten": HotDog.objects.filter(
            state …