To validate a list field with choices in a Django serializer, you can define the choices within the serializer field and use the 'validate' method to verify that input values are included in the permitted choices.

Here's an example:

class MySerializer(serializers.Serializer):
    CHOICES = [('choice1', 'Choice 1'), ('choice2', 'Choice 2'), ('choice3', 'Choice 3')]
    my_list_field = serializers.ListField(
        child=serializers.CharField(),
        choices=CHOICES
    )

    def validate_my_list_field(self, values):
        for value in values:
            if value not in dict(self.CHOICES):
                raise serializers.ValidationError(f'{value} is not a valid choice')
        return values

In this example, we define the choices as a list of tuples and use it to specify the 'choices' argument in the 'ListField'. We then create a 'validate_my_list_field' method to check if each value in the list is a valid choice. If not, a validation error is raised.

It's important to note that we utilize the 'dict' function to transform the list of tuples into a dictionary, making it easier to check if a value exists within the allowed choices.

Django Serializer List Field Validation with Choices

原文地址: https://www.cveoy.top/t/topic/m6Ql 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录