将具有多部分/表单数据的HTML/axios对象列表发布到DRF多部分解析器 [英] Post LIST OF OBJECTS from HTML/axios with multipart/form-data to DRF multipart parser
问题描述
这是我的序列化器:
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True) # reverse FK relation
ParentSerializer
还有一个图像字段,因此请求必须是多部分/表单数据,才能在单个请求中同时支持图像和数据.
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()
...因为我是手动创建 children
列表.
...because I'm manually creating the children
list.
问题是我无法通过axios/HTML表单执行相同的操作.正在发送的数据将转换为字符串.
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
.
推荐答案
您的字段必须以以下格式命名: children [0] key1
, children [0] key2
, children [1] key1
, children [1] key2
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
这篇关于将具有多部分/表单数据的HTML/axios对象列表发布到DRF多部分解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!