If you call the same model method with heavy calculations or database queries multiple times in the request-response cycle, the performance of the view might be very slow. In this recipe, you will learn about a pattern that you can use to cache the return value of a method for later repetitive use. Note that we are not using the Django cache framework here, we are just using what Python provides us by default.
Choose an app with a model that has a time-consuming method that will be used repetitively in the same request-response cycle.
This is a pattern that you can use to cache a method return value of a model for repetitive use in views, forms, or templates, as follows:
class SomeModel(models.Model): # ... def some_expensive_function(self): if not hasattr(self, "_expensive_value_cached"): # do some heavy calculations... # ... and save the result to result variable self._expensive_value_cached...