| 1 |
import warnings |
| 2 |
|
| 3 |
from django.core import checks |
| 4 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 5 |
from django.utils.functional import cached_property |
| 6 |
|
| 7 |
NOT_PROVIDED = object() |
| 8 |
|
| 9 |
|
| 10 |
class FieldCacheMixin: |
| 11 |
""" |
| 12 |
An API for working with the model's fields value cache. |
| 13 |
|
| 14 |
Subclasses must set self.cache_name to a unique entry for the cache - |
| 15 |
typically the field’s name. |
| 16 |
""" |
| 17 |
|
| 18 |
# RemovedInDjango60Warning. |
| 19 |
def get_cache_name(self): |
| 20 |
raise NotImplementedError |
| 21 |
|
| 22 |
@cached_property |
| 23 |
def cache_name(self): |
| 24 |
# RemovedInDjango60Warning: when the deprecation ends, replace with: |
| 25 |
# raise NotImplementedError |
| 26 |
cache_name = self.get_cache_name() |
| 27 |
warnings.warn( |
| 28 |
f"Override {self.__class__.__qualname__}.cache_name instead of " |
| 29 |
"get_cache_name().", |
| 30 |
RemovedInDjango60Warning, |
| 31 |
stacklevel=3, |
| 32 |
) |
| 33 |
return cache_name |
| 34 |
|
| 35 |
def get_cached_value(self, instance, default=NOT_PROVIDED): |
| 36 |
try: |
| 37 |
return instance._state.fields_cache[self.cache_name] |
| 38 |
except KeyError: |
| 39 |
if default is NOT_PROVIDED: |
| 40 |
raise |
| 41 |
return default |
| 42 |
|
| 43 |
def is_cached(self, instance): |
| 44 |
return self.cache_name in instance._state.fields_cache |
| 45 |
|
| 46 |
def set_cached_value(self, instance, value): |
| 47 |
instance._state.fields_cache[self.cache_name] = value |
| 48 |
|
| 49 |
def delete_cached_value(self, instance): |
| 50 |
del instance._state.fields_cache[self.cache_name] |
| 51 |
|
| 52 |
|
| 53 |
class CheckFieldDefaultMixin: |
| 54 |
_default_hint = ("<valid default>", "<invalid default>") |
| 55 |
|
| 56 |
def _check_default(self): |
| 57 |
if ( |
| 58 |
self.has_default() |
| 59 |
and self.default is not None |
| 60 |
and not callable(self.default) |
| 61 |
): |
| 62 |
return [ |
| 63 |
checks.Warning( |
| 64 |
"%s default should be a callable instead of an instance " |
| 65 |
"so that it's not shared between all field instances." |
| 66 |
% (self.__class__.__name__,), |
| 67 |
hint=( |
| 68 |
"Use a callable instead, e.g., use `%s` instead of " |
| 69 |
"`%s`." % self._default_hint |
| 70 |
), |
| 71 |
obj=self, |
| 72 |
id="fields.E010", |
| 73 |
) |
| 74 |
] |
| 75 |
else: |
| 76 |
return [] |
| 77 |
|
| 78 |
def check(self, **kwargs): |
| 79 |
errors = super().check(**kwargs) |
| 80 |
errors.extend(self._check_default()) |
| 81 |
return errors |