Complete worked example
python
from drf_lab import setup
setup()
from rest_framework import serializers
class Interval(serializers.Serializer):
low = serializers.IntegerField(min_value=0)
high = serializers.IntegerField(min_value=0)
score = serializers.FloatField(default=0.0)
def validate(self, values):
if values["low"] > values["high"]:
raise serializers.ValidationError("Bounds are not ordered")
return values
def codes(value):
if isinstance(value, dict):
return {str(key): codes(item) for key, item in value.items()}
if isinstance(value, list):
return [codes(item) for item in value]
return value.code
def inspect_example(payload):
serializer = Interval(data=payload, many=True)
if serializer.is_valid():
return {"value": [dict(item) for item in serializer.validated_data]}
return {"errors": codes(serializer.errors)}- Reasoning
- The serializer first validates field types and bounds, then runs the interval invariant. A failure that concerns the combination is attached to non_field_errors. Errors inside a submitted list retain the item index, allowing a client to identify which item needs correction. The helper converts ErrorDetail objects to their stable codes and stringifies index keys for a JSON-compatible public result. It does not flatten every failure into the first item or return the entire submitted payload. Good error reporting preserves location while limiting unnecessary data exposure.