【发布时间】: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