django rest framework: set field-level error from serializer validate() method

前端 未结 4 1440
忘掉有多难
忘掉有多难 2021-02-02 07:08

I have a serializer that validates fields based on the values of other fields, In the error response I would like to show each field error as a field error as opposed to showing

4条回答
  •  甜味超标
    2021-02-02 07:43

    In case you are using built-in validators in DRF (which are in-fact django core validators) you have to preprocess django ValidationError coming from validator with a function get_error_detail drf is using for this purpose.

    def _validate_min_value(self, data, key):
            try:
                MinValueValidator(Decimal('0.01'))(data.get(key))
            except ValidationErrorDjango as exc:
                raise ValidationError(
                    {key: get_error_detail(exc)}
                )
    

    Note that ValidationErrorDjango is a ValidationError from django.core.exceptions, while ValidationError is a one from rest_framework.exceptions

提交回复
热议问题