validators.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. """
  2. We perform uniqueness checks explicitly on the serializer class, rather
  3. the using Django's `.full_clean()`.
  4. This gives us better separation of concerns, allows us to use single-step
  5. object creation, and makes it possible to switch between using the implicit
  6. `ModelSerializer` class and an equivalent explicit `Serializer` class.
  7. """
  8. from django.db import DataError
  9. from django.utils.translation import gettext_lazy as _
  10. from rest_framework.exceptions import ValidationError
  11. from rest_framework.utils.representation import smart_repr
  12. # Robust filter and exist implementations. Ensures that queryset.exists() for
  13. # an invalid value returns `False`, rather than raising an error.
  14. # Refs https://github.com/encode/django-rest-framework/issues/3381
  15. def qs_exists(queryset):
  16. try:
  17. return queryset.exists()
  18. except (TypeError, ValueError, DataError):
  19. return False
  20. def qs_filter(queryset, **kwargs):
  21. try:
  22. return queryset.filter(**kwargs)
  23. except (TypeError, ValueError, DataError):
  24. return queryset.none()
  25. class UniqueValidator:
  26. """
  27. Validator that corresponds to `unique=True` on a model field.
  28. Should be applied to an individual field on the serializer.
  29. """
  30. message = _('This field must be unique.')
  31. requires_context = True
  32. def __init__(self, queryset, message=None, lookup='exact'):
  33. self.queryset = queryset
  34. self.message = message or self.message
  35. self.lookup = lookup
  36. def filter_queryset(self, value, queryset, field_name):
  37. """
  38. Filter the queryset to all instances matching the given attribute.
  39. """
  40. filter_kwargs = {'%s__%s' % (field_name, self.lookup): value}
  41. return qs_filter(queryset, **filter_kwargs)
  42. def exclude_current_instance(self, queryset, instance):
  43. """
  44. If an instance is being updated, then do not include
  45. that instance itself as a uniqueness conflict.
  46. """
  47. if instance is not None:
  48. return queryset.exclude(pk=instance.pk)
  49. return queryset
  50. def __call__(self, value, serializer_field):
  51. # Determine the underlying model field name. This may not be the
  52. # same as the serializer field name if `source=<>` is set.
  53. field_name = serializer_field.source_attrs[-1]
  54. # Determine the existing instance, if this is an update operation.
  55. instance = getattr(serializer_field.parent, 'instance', None)
  56. queryset = self.queryset
  57. queryset = self.filter_queryset(value, queryset, field_name)
  58. queryset = self.exclude_current_instance(queryset, instance)
  59. if qs_exists(queryset):
  60. raise ValidationError(self.message, code='unique')
  61. def __repr__(self):
  62. return '<%s(queryset=%s)>' % (
  63. self.__class__.__name__,
  64. smart_repr(self.queryset)
  65. )
  66. class UniqueTogetherValidator:
  67. """
  68. Validator that corresponds to `unique_together = (...)` on a model class.
  69. Should be applied to the serializer class, not to an individual field.
  70. """
  71. message = _('The fields {field_names} must make a unique set.')
  72. missing_message = _('This field is required.')
  73. requires_context = True
  74. def __init__(self, queryset, fields, message=None):
  75. self.queryset = queryset
  76. self.fields = fields
  77. self.message = message or self.message
  78. def enforce_required_fields(self, attrs, serializer):
  79. """
  80. The `UniqueTogetherValidator` always forces an implied 'required'
  81. state on the fields it applies to.
  82. """
  83. if serializer.instance is not None:
  84. return
  85. missing_items = {
  86. field_name: self.missing_message
  87. for field_name in self.fields
  88. if serializer.fields[field_name].source not in attrs
  89. }
  90. if missing_items:
  91. raise ValidationError(missing_items, code='required')
  92. def filter_queryset(self, attrs, queryset, serializer):
  93. """
  94. Filter the queryset to all instances matching the given attributes.
  95. """
  96. # field names => field sources
  97. sources = [
  98. serializer.fields[field_name].source
  99. for field_name in self.fields
  100. ]
  101. # If this is an update, then any unprovided field should
  102. # have it's value set based on the existing instance attribute.
  103. if serializer.instance is not None:
  104. for source in sources:
  105. if source not in attrs:
  106. attrs[source] = getattr(serializer.instance, source)
  107. # Determine the filter keyword arguments and filter the queryset.
  108. filter_kwargs = {
  109. source: attrs[source]
  110. for source in sources
  111. }
  112. return qs_filter(queryset, **filter_kwargs)
  113. def exclude_current_instance(self, attrs, queryset, instance):
  114. """
  115. If an instance is being updated, then do not include
  116. that instance itself as a uniqueness conflict.
  117. """
  118. if instance is not None:
  119. return queryset.exclude(pk=instance.pk)
  120. return queryset
  121. def __call__(self, attrs, serializer):
  122. self.enforce_required_fields(attrs, serializer)
  123. queryset = self.queryset
  124. queryset = self.filter_queryset(attrs, queryset, serializer)
  125. queryset = self.exclude_current_instance(attrs, queryset, serializer.instance)
  126. # Ignore validation if any field is None
  127. checked_values = [
  128. value for field, value in attrs.items() if field in self.fields
  129. ]
  130. if None not in checked_values and qs_exists(queryset):
  131. field_names = ', '.join(self.fields)
  132. message = self.message.format(field_names=field_names)
  133. raise ValidationError(message, code='unique')
  134. def __repr__(self):
  135. return '<%s(queryset=%s, fields=%s)>' % (
  136. self.__class__.__name__,
  137. smart_repr(self.queryset),
  138. smart_repr(self.fields)
  139. )
  140. class BaseUniqueForValidator:
  141. message = None
  142. missing_message = _('This field is required.')
  143. requires_context = True
  144. def __init__(self, queryset, field, date_field, message=None):
  145. self.queryset = queryset
  146. self.field = field
  147. self.date_field = date_field
  148. self.message = message or self.message
  149. def enforce_required_fields(self, attrs):
  150. """
  151. The `UniqueFor<Range>Validator` classes always force an implied
  152. 'required' state on the fields they are applied to.
  153. """
  154. missing_items = {
  155. field_name: self.missing_message
  156. for field_name in [self.field, self.date_field]
  157. if field_name not in attrs
  158. }
  159. if missing_items:
  160. raise ValidationError(missing_items, code='required')
  161. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  162. raise NotImplementedError('`filter_queryset` must be implemented.')
  163. def exclude_current_instance(self, attrs, queryset, instance):
  164. """
  165. If an instance is being updated, then do not include
  166. that instance itself as a uniqueness conflict.
  167. """
  168. if instance is not None:
  169. return queryset.exclude(pk=instance.pk)
  170. return queryset
  171. def __call__(self, attrs, serializer):
  172. # Determine the underlying model field names. These may not be the
  173. # same as the serializer field names if `source=<>` is set.
  174. field_name = serializer.fields[self.field].source_attrs[-1]
  175. date_field_name = serializer.fields[self.date_field].source_attrs[-1]
  176. self.enforce_required_fields(attrs)
  177. queryset = self.queryset
  178. queryset = self.filter_queryset(attrs, queryset, field_name, date_field_name)
  179. queryset = self.exclude_current_instance(attrs, queryset, serializer.instance)
  180. if qs_exists(queryset):
  181. message = self.message.format(date_field=self.date_field)
  182. raise ValidationError({
  183. self.field: message
  184. }, code='unique')
  185. def __repr__(self):
  186. return '<%s(queryset=%s, field=%s, date_field=%s)>' % (
  187. self.__class__.__name__,
  188. smart_repr(self.queryset),
  189. smart_repr(self.field),
  190. smart_repr(self.date_field)
  191. )
  192. class UniqueForDateValidator(BaseUniqueForValidator):
  193. message = _('This field must be unique for the "{date_field}" date.')
  194. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  195. value = attrs[self.field]
  196. date = attrs[self.date_field]
  197. filter_kwargs = {}
  198. filter_kwargs[field_name] = value
  199. filter_kwargs['%s__day' % date_field_name] = date.day
  200. filter_kwargs['%s__month' % date_field_name] = date.month
  201. filter_kwargs['%s__year' % date_field_name] = date.year
  202. return qs_filter(queryset, **filter_kwargs)
  203. class UniqueForMonthValidator(BaseUniqueForValidator):
  204. message = _('This field must be unique for the "{date_field}" month.')
  205. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  206. value = attrs[self.field]
  207. date = attrs[self.date_field]
  208. filter_kwargs = {}
  209. filter_kwargs[field_name] = value
  210. filter_kwargs['%s__month' % date_field_name] = date.month
  211. return qs_filter(queryset, **filter_kwargs)
  212. class UniqueForYearValidator(BaseUniqueForValidator):
  213. message = _('This field must be unique for the "{date_field}" year.')
  214. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  215. value = attrs[self.field]
  216. date = attrs[self.date_field]
  217. filter_kwargs = {}
  218. filter_kwargs[field_name] = value
  219. filter_kwargs['%s__year' % date_field_name] = date.year
  220. return qs_filter(queryset, **filter_kwargs)