Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate the length of nested items in a serializer?

I am using Django Rest Framework 2.4. In an API where I am expecting a dictionary containing two keys:

{
  "category" : <category-id>,
  "items" : [{"title": <title>}, {"title": <title>}, {"title": <title>}, ....]
}

I have a ItemListSerializer that accepts this dictionary. category is a foreign key to the Category model hence we get that data. category has a limit property which

I have a list of items which is handled by a nested ItemSerializer with many set to True

However, I want to check if the total number of items don't cross the limit which is based upon the category ?

like image 230
Amogh Talpallikar Avatar asked Feb 11 '23 04:02

Amogh Talpallikar


2 Answers

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")
like image 158
Sam R. Avatar answered Feb 13 '23 22:02

Sam R.


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")
like image 40
Ghariani Mohamed Avatar answered Feb 13 '23 23:02

Ghariani Mohamed