问题描述
这是我的序列化程序:
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True) # reverse FK relation
ParentSerializer
也有一个图像字段,因此请求必须是 multipart/form-data 以在单个请求中同时支持图像和数据.
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
注意]
和键名之间没有点.
这篇关于将带有多部分/表单数据的 HTML/axios 对象列表发布到 DRF 多部分解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!