DRF 不会自动将请求体的媒体类型更改为 multipart/form-data
复现步骤
view.py
from rest_framework import generics from rest_framework import serializers from django.db import models class Book(models.Model): title = models.CharField(max_length=200) class BookSerializer(serializers.ModelSerializer): cover = serializers.FileField() class Meta: model = Book fields = ('cover',) class BooksView(generics.CreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer
urls.py
urlpatterns = [ ... path('api/books/', views.BooksView.as_view()), ... ]
预期行为
./manage.py generateschema openapi: 3.0.2 info: title: '' version: TODO paths: /api/books/: post: operationId: CreateBook parameters: [] requestBody: content: multipart/form-data: schema: required: - cover properties: cover: type: string format: binary responses: '200': content: application/json: schema: required: - cover properties: cover: type: string
实际行为
./manage.py generateschema openapi: 3.0.2 info: title: '' version: TODO paths: /api/books/: post: operationId: CreateBook parameters: [] requestBody: content: application/json: schema: required: - cover properties: cover: type: string responses: '200': content: application/json: schema: required: - cover properties: cover: type: string 这里有两件事发生了:
- 没有自动生成
multipart/form-data媒体类型的支持 FileField生成了不完整的 OpenAPI 方案: 它不包含format: binary。最后,它只应生成format: binary请求,因为你不能在中包含二进制字符串字段
内容来源: encode/django-rest-framework