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