Caching the method return value

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.

Getting ready

Choose an app with a model that has a time-consuming method that will be used repetitively in the same request-response cycle.

How to do it...

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): ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.