| 1 |
""" |
| 2 |
We perform uniqueness checks explicitly on the serializer class, rather |
| 3 |
the using Django's `.full_clean()`. |
| 4 |
|
| 5 |
This gives us better separation of concerns, allows us to use single-step |
| 6 |
object creation, and makes it possible to switch between using the implicit |
| 7 |
`ModelSerializer` class and an equivalent explicit `Serializer` class. |
| 8 |
""" |
| 9 |
from django.core.exceptions import FieldError |
| 10 |
from django.db import DataError |
| 11 |
from django.db.models import Exists |
| 12 |
from django.utils.translation import gettext_lazy as _ |
| 13 |
|
| 14 |
from rest_framework.exceptions import ValidationError |
| 15 |
from rest_framework.utils.representation import smart_repr |
| 16 |
|
| 17 |
|
| 18 |
# Robust filter and exist implementations. Ensures that queryset.exists() for |
| 19 |
# an invalid value returns `False`, rather than raising an error. |
| 20 |
# Refs https://github.com/encode/django-rest-framework/issues/3381 |
| 21 |
def qs_exists(queryset): |
| 22 |
try: |
| 23 |
return queryset.exists() |
| 24 |
except (TypeError, ValueError, DataError): |
| 25 |
return False |
| 26 |
|
| 27 |
|
| 28 |
def qs_exists_with_condition(queryset, condition, against): |
| 29 |
if condition is None: |
| 30 |
return qs_exists(queryset) |
| 31 |
try: |
| 32 |
# use the same query as UniqueConstraint.validate |
| 33 |
# https://github.com/django/django/blob/7ba2a0db20c37a5b1500434ca4ed48022311c171/django/db/models/constraints.py#L672 |
| 34 |
return (condition & Exists(queryset.filter(condition))).check(against) |
| 35 |
except (TypeError, ValueError, DataError, FieldError): |
| 36 |
return False |
| 37 |
|
| 38 |
|
| 39 |
def qs_filter(queryset, **kwargs): |
| 40 |
try: |
| 41 |
return queryset.filter(**kwargs) |
| 42 |
except (TypeError, ValueError, DataError): |
| 43 |
return queryset.none() |
| 44 |
|
| 45 |
|
| 46 |
def _check_single_instance(serializer, instance, validator): |
| 47 |
""" |
| 48 |
Uniqueness validators need a single model instance in order to exclude |
| 49 |
the object being updated from the uniqueness check. |
| 50 |
|
| 51 |
When a serializer is used with `many=True` and a queryset or list is |
| 52 |
passed as the `instance`, the child serializer's `instance` will be that |
| 53 |
queryset or list, unless `ListSerializer.run_child_validation()` has been |
| 54 |
overridden to set `child.instance` for each item. Raise a clear error in |
| 55 |
that case rather than an `AttributeError` when accessing `instance.pk`. |
| 56 |
""" |
| 57 |
if ( |
| 58 |
instance is not None and |
| 59 |
getattr(serializer.parent, 'many', False) and |
| 60 |
not hasattr(instance, 'pk') |
| 61 |
): |
| 62 |
raise RuntimeError( |
| 63 |
'`%s` cannot determine the current instance during a multiple ' |
| 64 |
'update. Override `ListSerializer.run_child_validation()` to set ' |
| 65 |
'`child.instance` before validation.' % validator.__class__.__name__ |
| 66 |
) |
| 67 |
|
| 68 |
|
| 69 |
class UniqueValidator: |
| 70 |
""" |
| 71 |
Validator that corresponds to `unique=True` on a model field. |
| 72 |
|
| 73 |
Should be applied to an individual field on the serializer. |
| 74 |
""" |
| 75 |
message = _('This field must be unique.') |
| 76 |
requires_context = True |
| 77 |
|
| 78 |
def __init__(self, queryset, message=None, lookup='exact'): |
| 79 |
self.queryset = queryset |
| 80 |
self.message = message or self.message |
| 81 |
self.lookup = lookup |
| 82 |
|
| 83 |
def filter_queryset(self, value, queryset, field_name): |
| 84 |
""" |
| 85 |
Filter the queryset to all instances matching the given attribute. |
| 86 |
""" |
| 87 |
filter_kwargs = {'%s__%s' % (field_name, self.lookup): value} |
| 88 |
return qs_filter(queryset, **filter_kwargs) |
| 89 |
|
| 90 |
def exclude_current_instance(self, queryset, instance): |
| 91 |
""" |
| 92 |
If an instance is being updated, then do not include |
| 93 |
that instance itself as a uniqueness conflict. |
| 94 |
""" |
| 95 |
if instance is not None: |
| 96 |
return queryset.exclude(pk=instance.pk) |
| 97 |
return queryset |
| 98 |
|
| 99 |
def __call__(self, value, serializer_field): |
| 100 |
# Determine the underlying model field name. This may not be the |
| 101 |
# same as the serializer field name if `source=<>` is set. |
| 102 |
field_name = serializer_field.source_attrs[-1] |
| 103 |
# Determine the existing instance, if this is an update operation. |
| 104 |
serializer = serializer_field.parent |
| 105 |
instance = getattr(serializer, 'instance', None) |
| 106 |
_check_single_instance(serializer, instance, self) |
| 107 |
|
| 108 |
queryset = self.queryset |
| 109 |
queryset = self.filter_queryset(value, queryset, field_name) |
| 110 |
queryset = self.exclude_current_instance(queryset, instance) |
| 111 |
if qs_exists(queryset): |
| 112 |
raise ValidationError(self.message, code='unique') |
| 113 |
|
| 114 |
def __repr__(self): |
| 115 |
return '<%s(queryset=%s)>' % ( |
| 116 |
self.__class__.__name__, |
| 117 |
smart_repr(self.queryset) |
| 118 |
) |
| 119 |
|
| 120 |
def __eq__(self, other): |
| 121 |
if not isinstance(other, self.__class__): |
| 122 |
return NotImplemented |
| 123 |
return (self.message == other.message |
| 124 |
and self.requires_context == other.requires_context |
| 125 |
and self.queryset == other.queryset |
| 126 |
and self.lookup == other.lookup |
| 127 |
) |
| 128 |
|
| 129 |
|
| 130 |
class UniqueTogetherValidator: |
| 131 |
""" |
| 132 |
Validator that corresponds to `unique_together = (...)` on a model class. |
| 133 |
|
| 134 |
Should be applied to the serializer class, not to an individual field. |
| 135 |
""" |
| 136 |
message = _('The fields {field_names} must make a unique set.') |
| 137 |
missing_message = _('This field is required.') |
| 138 |
requires_context = True |
| 139 |
code = 'unique' |
| 140 |
|
| 141 |
def __init__(self, queryset, fields, message=None, condition_fields=None, condition=None, code=None, nulls_distinct=None): |
| 142 |
self.queryset = queryset |
| 143 |
self.fields = fields |
| 144 |
self.message = message or self.message |
| 145 |
self.condition_fields = [] if condition_fields is None else condition_fields |
| 146 |
self.condition = condition |
| 147 |
self.code = code or self.code |
| 148 |
self.nulls_distinct = nulls_distinct |
| 149 |
|
| 150 |
def enforce_required_fields(self, attrs, serializer): |
| 151 |
""" |
| 152 |
The `UniqueTogetherValidator` always forces an implied 'required' |
| 153 |
state on the fields it applies to. |
| 154 |
""" |
| 155 |
if serializer.instance is not None: |
| 156 |
return |
| 157 |
|
| 158 |
missing_items = { |
| 159 |
field_name: self.missing_message |
| 160 |
for field_name in (*self.fields, *self.condition_fields) |
| 161 |
if serializer.fields[field_name].source not in attrs |
| 162 |
} |
| 163 |
if missing_items: |
| 164 |
raise ValidationError(missing_items, code='required') |
| 165 |
|
| 166 |
def filter_queryset(self, attrs, queryset, serializer): |
| 167 |
""" |
| 168 |
Filter the queryset to all instances matching the given attributes. |
| 169 |
""" |
| 170 |
# field names => field sources |
| 171 |
sources = [ |
| 172 |
serializer.fields[field_name].source |
| 173 |
for field_name in self.fields |
| 174 |
] |
| 175 |
|
| 176 |
# If this is an update, then any unprovided field should |
| 177 |
# have it's value set based on the existing instance attribute. |
| 178 |
if serializer.instance is not None: |
| 179 |
for source in sources: |
| 180 |
if source not in attrs: |
| 181 |
attrs[source] = getattr(serializer.instance, source) |
| 182 |
|
| 183 |
# Determine the filter keyword arguments and filter the queryset. |
| 184 |
filter_kwargs = { |
| 185 |
source: attrs[source] |
| 186 |
for source in sources |
| 187 |
} |
| 188 |
return qs_filter(queryset, **filter_kwargs) |
| 189 |
|
| 190 |
def exclude_current_instance(self, attrs, queryset, instance): |
| 191 |
""" |
| 192 |
If an instance is being updated, then do not include |
| 193 |
that instance itself as a uniqueness conflict. |
| 194 |
""" |
| 195 |
if instance is not None: |
| 196 |
return queryset.exclude(pk=instance.pk) |
| 197 |
return queryset |
| 198 |
|
| 199 |
def __call__(self, attrs, serializer): |
| 200 |
_check_single_instance(serializer, serializer.instance, self) |
| 201 |
self.enforce_required_fields(attrs, serializer) |
| 202 |
queryset = self.queryset |
| 203 |
queryset = self.filter_queryset(attrs, queryset, serializer) |
| 204 |
queryset = self.exclude_current_instance(attrs, queryset, serializer.instance) |
| 205 |
|
| 206 |
checked_names = [ |
| 207 |
serializer.fields[field_name].source for field_name in self.fields |
| 208 |
] |
| 209 |
# Ignore validation if any field is None |
| 210 |
if serializer.instance is None: |
| 211 |
checked_values = [attrs[field_name] for field_name in checked_names] |
| 212 |
else: |
| 213 |
# Ignore validation if all field values are unchanged |
| 214 |
checked_values = [ |
| 215 |
attrs[field_name] |
| 216 |
for field_name in checked_names |
| 217 |
if attrs[field_name] != getattr(serializer.instance, field_name) |
| 218 |
] |
| 219 |
|
| 220 |
condition_sources = (serializer.fields[field_name].source for field_name in self.condition_fields) |
| 221 |
condition_kwargs = { |
| 222 |
source: attrs[source] |
| 223 |
if source in attrs |
| 224 |
else getattr(serializer.instance, source) |
| 225 |
for source in condition_sources |
| 226 |
} |
| 227 |
if checked_values: |
| 228 |
# Skip validation for None values unless nulls_distinct is False |
| 229 |
if self.nulls_distinct is not False and None in checked_values: |
| 230 |
return |
| 231 |
if qs_exists_with_condition(queryset, self.condition, condition_kwargs): |
| 232 |
field_names = ', '.join(self.fields) |
| 233 |
message = self.message.format(field_names=field_names) |
| 234 |
raise ValidationError(message, code=self.code) |
| 235 |
|
| 236 |
def __repr__(self): |
| 237 |
return '<{}({})>'.format( |
| 238 |
self.__class__.__name__, |
| 239 |
', '.join( |
| 240 |
f'{attr}={smart_repr(getattr(self, attr))}' |
| 241 |
for attr in ('queryset', 'fields', 'condition', 'nulls_distinct') |
| 242 |
if getattr(self, attr) is not None) |
| 243 |
) |
| 244 |
|
| 245 |
def __eq__(self, other): |
| 246 |
if not isinstance(other, self.__class__): |
| 247 |
return NotImplemented |
| 248 |
return (self.message == other.message |
| 249 |
and self.requires_context == other.requires_context |
| 250 |
and self.missing_message == other.missing_message |
| 251 |
and self.queryset == other.queryset |
| 252 |
and self.fields == other.fields |
| 253 |
and self.code == other.code |
| 254 |
and self.nulls_distinct == other.nulls_distinct |
| 255 |
) |
| 256 |
|
| 257 |
|
| 258 |
class ProhibitSurrogateCharactersValidator: |
| 259 |
message = _('Surrogate characters are not allowed: U+{code_point:X}.') |
| 260 |
code = 'surrogate_characters_not_allowed' |
| 261 |
|
| 262 |
def __call__(self, value): |
| 263 |
for surrogate_character in (ch for ch in str(value) |
| 264 |
if 0xD800 <= ord(ch) <= 0xDFFF): |
| 265 |
message = self.message.format(code_point=ord(surrogate_character)) |
| 266 |
raise ValidationError(message, code=self.code) |
| 267 |
|
| 268 |
def __eq__(self, other): |
| 269 |
if not isinstance(other, self.__class__): |
| 270 |
return NotImplemented |
| 271 |
return (self.message == other.message |
| 272 |
and self.code == other.code |
| 273 |
) |
| 274 |
|
| 275 |
|
| 276 |
class BaseUniqueForValidator: |
| 277 |
message = None |
| 278 |
missing_message = _('This field is required.') |
| 279 |
requires_context = True |
| 280 |
|
| 281 |
def __init__(self, queryset, field, date_field, message=None): |
| 282 |
self.queryset = queryset |
| 283 |
self.field = field |
| 284 |
self.date_field = date_field |
| 285 |
self.message = message or self.message |
| 286 |
|
| 287 |
def enforce_required_fields(self, attrs): |
| 288 |
""" |
| 289 |
The `UniqueFor<Range>Validator` classes always force an implied |
| 290 |
'required' state on the fields they are applied to. |
| 291 |
""" |
| 292 |
missing_items = { |
| 293 |
field_name: self.missing_message |
| 294 |
for field_name in [self.field, self.date_field] |
| 295 |
if field_name not in attrs |
| 296 |
} |
| 297 |
if missing_items: |
| 298 |
raise ValidationError(missing_items, code='required') |
| 299 |
|
| 300 |
def filter_queryset(self, attrs, queryset, field_name, date_field_name): |
| 301 |
raise NotImplementedError('`filter_queryset` must be implemented.') |
| 302 |
|
| 303 |
def exclude_current_instance(self, attrs, queryset, instance): |
| 304 |
""" |
| 305 |
If an instance is being updated, then do not include |
| 306 |
that instance itself as a uniqueness conflict. |
| 307 |
""" |
| 308 |
if instance is not None: |
| 309 |
return queryset.exclude(pk=instance.pk) |
| 310 |
return queryset |
| 311 |
|
| 312 |
def __call__(self, attrs, serializer): |
| 313 |
# Determine the underlying model field names. These may not be the |
| 314 |
# same as the serializer field names if `source=<>` is set. |
| 315 |
field_name = serializer.fields[self.field].source_attrs[-1] |
| 316 |
date_field_name = serializer.fields[self.date_field].source_attrs[-1] |
| 317 |
|
| 318 |
_check_single_instance(serializer, serializer.instance, self) |
| 319 |
self.enforce_required_fields(attrs) |
| 320 |
queryset = self.queryset |
| 321 |
queryset = self.filter_queryset(attrs, queryset, field_name, date_field_name) |
| 322 |
queryset = self.exclude_current_instance(attrs, queryset, serializer.instance) |
| 323 |
if qs_exists(queryset): |
| 324 |
message = self.message.format(date_field=self.date_field) |
| 325 |
raise ValidationError({ |
| 326 |
self.field: message |
| 327 |
}, code='unique') |
| 328 |
|
| 329 |
def __eq__(self, other): |
| 330 |
if not isinstance(other, self.__class__): |
| 331 |
return NotImplemented |
| 332 |
return (self.message == other.message |
| 333 |
and self.missing_message == other.missing_message |
| 334 |
and self.requires_context == other.requires_context |
| 335 |
and self.queryset == other.queryset |
| 336 |
and self.field == other.field |
| 337 |
and self.date_field == other.date_field |
| 338 |
) |
| 339 |
|
| 340 |
def __repr__(self): |
| 341 |
return '<%s(queryset=%s, field=%s, date_field=%s)>' % ( |
| 342 |
self.__class__.__name__, |
| 343 |
smart_repr(self.queryset), |
| 344 |
smart_repr(self.field), |
| 345 |
smart_repr(self.date_field) |
| 346 |
) |
| 347 |
|
| 348 |
|
| 349 |
class UniqueForDateValidator(BaseUniqueForValidator): |
| 350 |
message = _('This field must be unique for the "{date_field}" date.') |
| 351 |
|
| 352 |
def filter_queryset(self, attrs, queryset, field_name, date_field_name): |
| 353 |
value = attrs[self.field] |
| 354 |
date = attrs[self.date_field] |
| 355 |
|
| 356 |
filter_kwargs = {} |
| 357 |
filter_kwargs[field_name] = value |
| 358 |
filter_kwargs['%s__day' % date_field_name] = date.day |
| 359 |
filter_kwargs['%s__month' % date_field_name] = date.month |
| 360 |
filter_kwargs['%s__year' % date_field_name] = date.year |
| 361 |
return qs_filter(queryset, **filter_kwargs) |
| 362 |
|
| 363 |
|
| 364 |
class UniqueForMonthValidator(BaseUniqueForValidator): |
| 365 |
message = _('This field must be unique for the "{date_field}" month.') |
| 366 |
|
| 367 |
def filter_queryset(self, attrs, queryset, field_name, date_field_name): |
| 368 |
value = attrs[self.field] |
| 369 |
date = attrs[self.date_field] |
| 370 |
|
| 371 |
filter_kwargs = {} |
| 372 |
filter_kwargs[field_name] = value |
| 373 |
filter_kwargs['%s__month' % date_field_name] = date.month |
| 374 |
return qs_filter(queryset, **filter_kwargs) |
| 375 |
|
| 376 |
|
| 377 |
class UniqueForYearValidator(BaseUniqueForValidator): |
| 378 |
message = _('This field must be unique for the "{date_field}" year.') |
| 379 |
|
| 380 |
def filter_queryset(self, attrs, queryset, field_name, date_field_name): |
| 381 |
value = attrs[self.field] |
| 382 |
date = attrs[self.date_field] |
| 383 |
|
| 384 |
filter_kwargs = {} |
| 385 |
filter_kwargs[field_name] = value |
| 386 |
filter_kwargs['%s__year' % date_field_name] = date.year |
| 387 |
return qs_filter(queryset, **filter_kwargs) |