Skip to content

Conversation

@lrnt
Copy link
Contributor

@lrnt lrnt commented Jan 11, 2016

Parsing multipart data using a nested serializer with a list can result in incorrect behavior. If the list contains more than one item, only the last item will be saved.

Here is an example:

class NestedSerializer(serializers.Serializer):
    example = serializers.MultipleChoiceField(choices=[1, 2, 3])

class TestSerializer(serializers.Serializer):
    nested = NestedSerializer()

When you send the following data formatted as JSON everything will be fine:

{
    'nested': {
        'example': [1, 2],
    }
}
#   --->
{
    'nested': {
        'example': [1, 2],
    }
}

However, when you send the same data formatted as multipart data the serialized object will only take the last element of the list:

{
    'nested.example': [1, 2]
}
#   --->
{
    'nested' {
        'example': 2,
    }
}

The bug is situated in parse_html_dict(dictionary, prefix='') in rest_framework.utils.html. This function takes and returns a new MultiValueDict. A key in a MultiValueDict can have multiple values, this is how a list is represented. When accessing a key in a MultiValueDict only the last element of the list is returned.

This can be easily solved by using .getlist() and .setlist() when getting and setting the value of the MultiValueDict.

Closes #3710.

lrnt added 2 commits January 11, 2016 11:47
TestNestedSerializerWithList checks if a list (a MulitpleChoiceField in
this case) in a nested serializer is correctly parsed from json or
multipart formatted data.
It is possible that a key in a MultiValueDict has multiple values, lists
are represented this way. When accessing a key in a MultiValueDict
it only returns the last element of that key. This becomes a problem
when parsing an html dict with a list inside of it.

To fix this problem we have to get and set the value using .getlist()
and .setlist().

This commit solves a bug that caused a list in a nested serializer to
not being properly parsed if it was sent as multipart formated data.
@lovelydinosaur
Copy link
Contributor

Yup, looks good. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants