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 ?
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")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With