mixins.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from django.core import checks
  2. NOT_PROVIDED = object()
  3. class FieldCacheMixin:
  4. """Provide an API for working with the model's fields value cache."""
  5. def get_cache_name(self):
  6. raise NotImplementedError
  7. def get_cached_value(self, instance, default=NOT_PROVIDED):
  8. cache_name = self.get_cache_name()
  9. try:
  10. return instance._state.fields_cache[cache_name]
  11. except KeyError:
  12. if default is NOT_PROVIDED:
  13. raise
  14. return default
  15. def is_cached(self, instance):
  16. return self.get_cache_name() in instance._state.fields_cache
  17. def set_cached_value(self, instance, value):
  18. instance._state.fields_cache[self.get_cache_name()] = value
  19. def delete_cached_value(self, instance):
  20. del instance._state.fields_cache[self.get_cache_name()]
  21. class CheckFieldDefaultMixin:
  22. _default_hint = ('<valid default>', '<invalid default>')
  23. def _check_default(self):
  24. if self.has_default() and self.default is not None and not callable(self.default):
  25. return [
  26. checks.Warning(
  27. "%s default should be a callable instead of an instance "
  28. "so that it's not shared between all field instances." % (
  29. self.__class__.__name__,
  30. ),
  31. hint=(
  32. 'Use a callable instead, e.g., use `%s` instead of '
  33. '`%s`.' % self._default_hint
  34. ),
  35. obj=self,
  36. id='fields.E010',
  37. )
  38. ]
  39. else:
  40. return []
  41. def check(self, **kwargs):
  42. errors = super().check(**kwargs)
  43. errors.extend(self._check_default())
  44. return errors