March 2020
Intermediate to advanced
608 pages
17h 17m
English
In this generic example, the method checks whether the _expensive_value_cached attribute exists for the model instance. If it doesn't exist, time-consuming calculations are performed and the result is assigned to this new attribute. At the end of the method, the cached value is returned. Of course, if you have several weighty methods, you will need to use different attribute names to save each calculated value.
You can now use something such as {{ object.some_expensive_function }} in the header and footer of a template, and the time-consuming calculations will be done just once.
In a template, you can also use the function in both the {% if %} condition and the output of the value, as follows:
{% if object.some_expensive_function ...