Skip to content

initial_data not as expected with many=True #5345

Closed
@daggaz

Description

@daggaz

Checklist

  • I have verified that that issue exists against the master branch of Django REST framework.
  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • This is not a usage question. (Those should be directed to the discussion group instead.)
  • This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • I have reduced the issue to the simplest possible case.
  • I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

Steps to reproduce

Create a test serializer that uses initial_data:

class TestSerializer(serializers.Serializer):
    number = serializers.IntegerField()
    def validate(self, attrs):
        print self.initial_data
        return attrs

Use it:

>>> serializer = TestSerializer(data={'number': 1})
>>> serializer.is_valid()
{'number': 1}

initial_data is a dict as expected

Use it with many = True:

>>> list_serializer = TestSerializer(data=[{'number': 1}, {'number': 1}], many=True)
>>> list_serializer.is_valid()
[{'number': 1}, {'number': 2}]
[{'number': 1}, {'number': 2}]

initial_data is a list, even though as far as the TestSerializer class is concerned, it operates on individual objects.

Expected behavior

The ListSerializer should update the initial_data of it's child serializer as it is iterating. The expected output would be:

>>> list_serializer = TestSerializer(data=[{'number': 1}, {'number': 1}], many=True)
>>> list_serializer.is_valid()
{'number': 1}
{'number': 2}

Actual behavior

Both times the TestSerializer class is used it gets initial_data as a list. Therefore the class needs to know that it was called from a ListSerializer context to operate. This is surprising.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions