-
-
Save t0mab/e6b26a0b0dd34df4b38d522587ba2630 to your computer and use it in GitHub Desktop.
Memoize Django model's method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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