[Django]-How to validate the length of nested items in a serializer?

4👍

Use validate() method on the serializer to check the length and raise ValidationError if it doesn’t pass:

class YourSerializer(serializers.Serializer):
      items = ItemSerializer(many=True)

      def validate(self, attrs):
           if len(attrs['items']) > YOUR_MAX:
               raise serializers.ValidationError("Invalid number of items")
👤Sam R.

5👍

You can create a validate_items()

Django rest framework will display the error as a field error for that field. so parsing the response will be easier

class YourSerializer(serializers.Serializer):
    items = ItemSerializer(many=True)

    def validate_items(self, items):
        if len(items) > YOUR_MAX:
            raise serializers.ValidationError("Invalid number of items")

Leave a comment