Skip to content

Instantly share code, notes, and snippets.

@martync
Last active July 3, 2018 09:37
Show Gist options
  • Save martync/11040284 to your computer and use it in GitHub Desktop.
Save martync/11040284 to your computer and use it in GitHub Desktop.
Memoize Django model's method.
import functools
def memoize_django_model_method(obj):
@functools.wraps(obj)
def memoizer(*args, **kwargs):
# Get the model instance
instance = args[0]
if not hasattr(instance, "__memoize_cache"):
# If not present yet, add a dictionnary to store values for this instance.
# This dictionnary keys will be filled by the method name + args.
instance.__memoize_cache = {}
# Creating the key base on method_name + args passed to the function
key = str(obj.__name__) + str(kwargs)
if not key in instance.__memoize_cache:
# This is the first time we call this function on this instance with thoses args.
instance.__memoize_cache[key] = obj(*args, **kwargs)
# Return the value stored.
return instance.__memoize_cache[key]
return memoizer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment