我收到一个包含几个文件的数组。我的 request.data 如下所示:
<QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>]
但是,如果我尝试像这样解析图像:
request.data['image']
我只能看到最后一个图像,django Rest框架将其识别为文件对象,而不是列表。 如果我尝试迭代它,我只能看到字节。
我正在使用 ModelViewset 并添加了这个解析器
parser_classes = (MultiPartParser, FormParser)
最佳答案
QueryDict
有一个特殊的函数来获取与特定键关联的所有值:getlist(key)
[doc] 。所以你可以这样写:
request.data<b>.getlist('image')</b> # list of images
然后,您可以单独处理每个图像(例如在 for
循环中)。
或者像 documentation 中指定的那样:
Returns a list of the data with the requested key. Returns an empty list if the key doesn't exist and a default value wasn’t provided. It's guaranteed to return a list unless the<b>QueryDict.getlist(key, default=None)</b>
default
value provided is' a list.
如果您执行索引(如request.data[key]
),那么Python将调用__getitem__
在幕后,这将导致:
Returns the value for the given key. If the key has more than one value, it returns the last value. Raises<b>QueryDict.__getitem__(key)</b>
django.utils.datastructures.MultiValueDictKeyError
if the key does not exist. (This is a subclass of Python's standardKeyError
, so you can stick to catchingKeyError
.)
关于python - 如何使用 django Rest 框架解析多部分表单数据中的多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50505440/