Coverage for netbox/monkey.py: 100%
16 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
1from django.db.models import UniqueConstraint
2from rest_framework.utils.field_mapping import get_unique_error_message
3from rest_framework.validators import UniqueValidator
5__all__ = (
6 'get_unique_validators',
7)
10def get_unique_validators(field_name, model_field):
11 """
12 Extend Django REST Framework's get_unique_validators() function to attach a UniqueValidator to a field *only* if the
13 associated UniqueConstraint does NOT have a condition which references another field. See bug #19302.
14 """
15 field_set = {field_name}
16 conditions = {
17 c.condition
18 for c in model_field.model._meta.constraints
19 if isinstance(c, UniqueConstraint) and set(c.fields) == field_set
20 }
22 # START custom logic
23 conditions = {
24 cond for cond in conditions
25 if cond is None or cond.referenced_base_fields == field_set
26 }
27 # END custom logic
29 if getattr(model_field, 'unique', False):
30 conditions.add(None)
31 if not conditions:
32 return
33 unique_error_message = get_unique_error_message(model_field)
34 queryset = model_field.model._default_manager
35 for condition in conditions:
36 yield UniqueValidator(
37 queryset=queryset if condition is None else queryset.filter(condition),
38 message=unique_error_message
39 )