summaryrefslogtreecommitdiff
path: root/docs/ref/utils.txt
diff options
context:
space:
mode:
authorDaniele Procida <daniele@vurt.org>2013-08-07 18:47:07 +0100
committerTim Graham <timograham@gmail.com>2013-08-08 05:36:57 -0400
commite8ea55212bc1520da2e9b87af9990505c5baa000 (patch)
tree67a05b0b1e287cc8e71138c910d78ea0b48b43ba /docs/ref/utils.txt
parentd4c19a6e7e45f3ff4dbbb2424904b726709bb24f (diff)
[1.5.x] Fixed #20870 -- Documented django.utils.functional.cached_property
Backport of 7a2296eb5b from master
Diffstat (limited to 'docs/ref/utils.txt')
-rw-r--r--docs/ref/utils.txt44
1 files changed, 44 insertions, 0 deletions
diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt
index b31d6063c4..e386dc9a5b 100644
--- a/docs/ref/utils.txt
+++ b/docs/ref/utils.txt
@@ -449,6 +449,50 @@ Atom1Feed
.. module:: django.utils.functional
:synopsis: Functional programming tools.
+.. class:: cached_property(object)
+
+ The ``@cached_property`` decorator caches the result of a method with a
+ single ``self`` argument as a property. The cached result will persist as
+ long as the instance does.
+
+ Consider a typical case, where a view might need to call a model's method
+ to perform some computation, before placing the model instance into the
+ context, where the template might invoke the method once more::
+
+ # the model
+ class Person(models.Model):
+
+ def friends(self):
+ # expensive computation
+ ...
+ return friends
+
+ # in the view:
+ if person.friends():
+
+ # in the template:
+ {% for friend in person.friends %}
+
+ ``friends()`` will be called twice. Since the instance ``person`` in
+ the view and the template are the same, ``@cached_property`` can avoid
+ that::
+
+ from django.utils.functional import cached_property
+
+ @cached_property
+ def friends(self):
+ # expensive computation
+ ...
+ return friends
+
+ Note that as the method is now a property, in Python code it will need to
+ be invoked appropriately::
+
+ # in the view:
+ if person.friends:
+
+ You may clear the cached result using ``del person.friends``.
+
.. function:: allow_lazy(func, *resultclasses)
Django offers many utility functions (particularly in ``django.utils``) that