How to raise multiple ValidationError on Django?

2019-05-11 02:54发布

问题:

from rest_framework.exceptions import ValidationError

def to_representation(self, request_data):
    raise ValidationError({
        'field_name': ["Field not allowed to change"]
    })

In the example above how can I throw multiple validation errors? I want to throw them as dicts to show at the respective fields.

回答1:

You throw one ValidationError with multiple fields errors inside:

    raise ValidationError({
        'field_name_1': ["Field not allowed to change"],
        'field_name_2': ["Field not allowed to change"],
    })