mixins.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 (
  25. self.has_default()
  26. and self.default is not None
  27. and not callable(self.default)
  28. ):
  29. return [
  30. checks.Warning(
  31. "%s default should be a callable instead of an instance "
  32. "so that it's not shared between all field instances."
  33. % (self.__class__.__name__,),
  34. hint=(
  35. "Use a callable instead, e.g., use `%s` instead of "
  36. "`%s`." % self._default_hint
  37. ),
  38. obj=self,
  39. id="fields.E010",
  40. )
  41. ]
  42. else:
  43. return []
  44. def check(self, **kwargs):
  45. errors = super().check(**kwargs)
  46. errors.extend(self._check_default())
  47. return errors