【问题标题】:Create Nested Serialier Multi Objects in Django Rest Framework?在 Django Rest 框架中创建嵌套序列化器多对象?
【发布时间】:2018-04-06 07:00:11
【问题描述】:

我正在寻找在 Django Rest Framework 中创建嵌套串行多对象的解决方案?

我有 2 个模型:产品和照片(照片是存储所有产品照片的模型)。我创建的这个序列化程序是为了创建一个产品并上传这个产品的所有图像:

class PhotoUpdateSerializer(ModelSerializer):
    class Meta:
        model = Photo
        fields = [
            'image'
        ]

class ProductCreateSerializer(ModelSerializer):
    photos = ProductPhotosSerializer(many=True, write_only=True, required=False)
    class Meta:
        model = Product
        fields = [
            'id',
            'user',
            'name',
            'photos'
        ]

我的观点集:

class ProductCreateAPIView(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductCreateSerializer
    def create_product(self, request):
        newProduct = Product.objects.create(
           user = User.objects.get(id=request.POST.get('user')),
           name = request.POST.get('name', '')
        )
        newPhotos = Photo.objects.create(
           product = newProduct.id,
           image = request.POST.get('photos.image', '')
        )
        serializer = ProductCreateSerializer(newProduct, context={"request": request})
        return Response(serializer.data, status=200)

错误:Request.POST has no photos.image

当我打印(request.POST)时,像这张图一样使用 POSTMAN:

打印:{u'user': [u'2']}>。没有照片 POST?

【问题讨论】:

  • 您向她展示的错误意味着当您从前端发送请求时它缺少photos.image。确保您的表单可以正常上传图片并将其发送到后端。

标签: django django-rest-framework


【解决方案1】:

试试:image = request.data.get('image')

通常我会做的是 base 64 在源处对图像进行编码并在视图处对其进行解码。

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2019-06-14
    • 1970-01-01
    • 2018-12-13
    • 2022-06-25
    • 2020-07-07
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多