问题
This is my serializer:
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True) # reverse FK relation
ParentSerializer
also has an image field, so the request has to be multipart/form-data to support both image and data in a single request.
The following code/test works fine:
test_data = QueryDict('', mutable=True)
dictionary = {
'name': ['test'],
'children[0]': [{'key1': 'val1', 'key2': 'val2'}]
}
test_data.update(MultiValueDict(dictionary))
test_serializer = self.get_serializer(data=test_data)
test_serializer.is_valid(raise_exception=True)
test_instance = test_serializer.save()
...because I'm manually creating the children
list.
The problem is I'm not able to do the same through axios/HTML form. The data being sent is converted to string.
What are my options? I want to send list of child objects along with other data.
DRF v3.9
& Django v2.2
.
回答1:
Your fields must be named in the following form children[0]key1
, children[0]key2
, children[1]key1
, children[1]key2
Note that there is no dot .
between the ]
and the key name
来源:https://stackoverflow.com/questions/56908497/post-list-of-objects-from-html-axios-with-multipart-form-data-to-drf-multipart-p