Это своего рода хак, но это работает.
Вам нужно определить пользовательское поле и там вам нужно переопределить to_internal_value
метод поля.Например:
class CustomField(serializers.Field):
def __init__(self, custom_validation, *args, **kwargs):
self.custom_validation=custom_validation # <-- Here pass your custom validation regex
super(CustomField, self).__init__(*args, **kwargs)
def to_representation(self, obj):
return obj
def to_internal_value(self, obj):
try:
match = re.search(self.custom_validation, obj) # <-- validate the value against regex
if match:
return obj
except Exception as e:
pass
return None # <-- If exception occurs, return None
Или переопределить EmailField
следующим образом:
class CustomEmailField(serializer.EmailField):
def run_validation(self,*args, **kwargs):
try:
return super(CustomEmailField, self).run_validation(*args,**kwargs) # <-- Runs validation, but it fails, returns None
except:
return None
И использовать его в Сериализаторе следующим образом:
email = CustomField(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") # regex for email
Или
email = CustomEmailField()
И если вы хотите получить недопустимые значения из ListField
, вы можете переопределить to_representation
следующим образом:
class CustomListField(serializers.ListField):
def to_representation(self, data):
childs = super(CustomListField, self).to_representation(data)
new_childs = []
for child in childs:
if child:
new_childs.append(child)
return new_childs
Затем используйте его в Сериализаторе:
email_addresses = CustomListField(child=CustomEmailField(), required=False)