How can I check the length of nested elements in a serializer?
I am using Django Rest Framework 2.4. In the API where I expect a dictionary containing two keys:
{
"category" : <category-id>,
"items" : [{"title": <title>}, {"title": <title>}, {"title": <title>}, ....]
}
I have ItemListSerializer
one that accepts this dictionary. category is a foreign key to the category model, so we get this data. the category has a limiting property that
I have a list of items that are handled by a nested ItemSerializer with many settings to True
However, I want to check if the total number of items exceeds the category based limit?
source to share
Use the validate () method on the serializer to check the length and raise ValidationError
if it fails:
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")
source to share
You can create validate_items ()
The 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")
source to share