Hi everyone!
I have a quick question: Are custom template filters in Django CPU expensive?
I created this simple filter:
@register.filter
def get(dictionary, key):
return dictionary.get(key)
It just retrieves a value from a dictionary using a key. I’ve checked the Django documentation and searched online, but couldn’t find anything that suggests custom filters like this one are particularly costly in terms of performance.
Is there any reason to avoid using a filter like this in a template? Any hidden performance implications I should be aware of?
Thanks in advance!
Welcome @tomascimadorook !
Filters are a standard part of the Django template language. There are already about 60 filters built-in, so they’re expected to be used. Anything you write would just be more of the same.
What is making you think that this would be an issue?
(Expensive is a relative term. What you consider expensive, someone else might not. Template rendering is already a time-consuming operation, whether you consider using filters to be expensive is only something you can determine.)
I understand that this is not the point of the question, but I believe this filter in particular is not necessary, as dictionary keys can simply be accesed in Django by the dot notation e.g. {{ some_dict.some_key }}
.
One exception would be if you need to use key that is a variable, but this is not a common use case.