HackSoftware / Django-Styleguide

Django styleguide used in HackSoft projects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Exception handling and nested serializer with many=True

kitqee opened this issue · comments

There are the following serializers:

class ItemSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    count = serializers.DecimalField(max_digits=12, decimal_places=2)
    is_removed = serializers.BooleanField()


class DocumentSerializer(serializers.Serializer):
    comment = serializers.CharField()
    items = ItemSerializer(many=True, required=True, allow_empty=False)

Or

class DocumentSerializer(serializers.Serializer):
    comment = serializers.CharField()
    items = inline_serializer(many=True, fields={
        'id': serializers.IntegerField(),
        'count': serializers.DecimalField(max_digits=12, decimal_places=2),
        'is_removed': serializers.BooleanField()
    })

I expected the following error formatting on an invalid request:

{
    "errors": [
        {
            "message": "This field is required.",
            "code": "required",
            "field": "items.0.is_removed"
        },
        {
            "message": "This field is required.",
            "code": "required",
            "field": "items.1.is_removed"
        }
    ]
}

But I got:

{
    "errors": [
        {
            "is_removed": [
                {
                    "message": "This field is required.",
                    "code": "required"
                }
            ],
            "field": "items"
        },
        {
            "is_removed": [
                {
                    "message": "This field is required.",
                    "code": "required"
                }
            ],
            "field": "items"
        }
    ]
}

What's wrong? thanks

Hi, @aesfur !

Your serializers' structure looks valid, but it seems that you're not using the ErrorsFormatter, documented in the Error formatting section.

This, combined with the mechanism explained in the API exception handling section is the solution of your problem.

Cheers! 🙌

@wencakisa Hi!

I use the formatter from example.
But the examples above are not formatted correctly

Only this works as expected:
items = serializers.ListField(child=ItemSerializer())