我找到了一个在Django Rest Framework中创建嵌套Serialier多对象的解决方案?
我有2个型号:产品和照片(照片是存储产品所有照片的模型)。我创建的这个序列化器是为了创建一个Product&上传此产品的所有图片:
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?
答案 0 :(得分:0)
尝试:image = request.data.get('image')
通常我要做的是base 64对源处理的图像进行编码并在视图中对其进行解码。