v0.166.0
 1from typing import Any
 2
 3NOT_PROVIDED = object()
 4
 5
 6class FieldCacheMixin:
 7    """Provide an API for working with the model's fields value cache."""
 8
 9    def get_cache_name(self) -> str:
10        raise NotImplementedError
11
12    def get_cached_value(self, instance: Any, default: Any = NOT_PROVIDED) -> Any:
13        cache_name = self.get_cache_name()
14        try:
15            return instance._state.fields_cache[cache_name]
16        except KeyError:
17            if default is NOT_PROVIDED:
18                raise
19            return default
20
21    def is_cached(self, instance: Any) -> bool:
22        return self.get_cache_name() in instance._state.fields_cache
23
24    def set_cached_value(self, instance: Any, value: Any) -> None:
25        instance._state.fields_cache[self.get_cache_name()] = value
26
27    def delete_cached_value(self, instance: Any) -> None:
28        del instance._state.fields_cache[self.get_cache_name()]