DRF可浏览API如何上传文件并发送嵌套的JSON数据?

时间:2019-01-02 20:00:16

标签: json django file-upload django-rest-framework

我想使用django-rest-framework提供的可浏览的开发人员Web API与包含ImageField和嵌套Serializer的{​​{3}}进行交互。 / p>

使用此示例代码:

from django.db import models
from drf_writable_nested import WritableNestedModelSerializer
from rest_framework.serializers import ModelSerializer
from django.urls import include, path
from rest_framework import routers, viewsets


class House(models.Model):
    image = models.ImageField()


class Cat(models.Model):
    house = models.ForeignKey(House, related_name='cats', on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=50)


class CatSerializer(ModelSerializer):
    class Meta:
        model = Cat
        fields = '__all__'


class HouseSerializer(WritableNestedModelSerializer):
    cats = CatSerializer(many=True)

    class Meta:
        model = House
        fields = '__all__'


class HouseViewSet(viewsets.ModelViewSet):
    queryset = House.objects.all()
    serializer_class = HouseSerializer


router = routers.DefaultRouter()
router.register(r'houses', HouseViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

使用此版本的Python软件包:

$ pip freeze
Django==2.1.4
django-rest-framework==0.1.0
djangorestframework==3.9.0
drf-writable-nested==0.5.1
pytz==2018.7

HTML表单不支持嵌套JSON序列化:

WritableNestedModelSerializer

原始数据表单不支持发送二进制文件:

enter image description here

0 个答案:

没有答案