目前我正在开发一个图片库django项目。用户可以上传图像,然后将“结果”上传到每个图像。 我知道我必须覆盖更新(...)函数,但我认为我需要帮助这里使用Base64ImageFiled。
一步一步:
这是我目前的结构:
class Image(models.Model):
project = models.ForeignKey(Project)
image = models.ImageField(upload_to='images')
result = models.ImageField(upload_to='results')
class ImageSerializer(serializers.ModelSerializer):
project = ProjectSerializer(read_only=True, required=False)
image = Base64ImageField(max_length=None, use_url=False)
result = Base64ImageField(max_length=None, use_url=False, required=False)
class ProjectImagesViewSet(viewsets.ViewSet):
queryset = Image.objects.select_related('project').all()
serializer_class = ImageSerializer
def list(self, request, project_pk=None):
queryset = self.queryset.filter( project__name = project_pk)
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
def update(self, request, pk=None, project_pk=None):
print(request.data['result'])
???
答案 0 :(得分:2)
Django Rest Framework约定是使用partial_update而不是update(PATCH请求方法)。如果您将带有图像的PATCH请求发送到与检索url相同的URL,则应该更新。如果您在更新时需要其他功能,则可以定义:
class ProjectImagesViewSet(viewsets.ViewSet):
#.....
def partial_update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.serialize(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
#.... Your code ....
serializer.save()
return Response(serializer.data)
修改强> 尝试这些更改:
class ImageSerializer(serializers.ModelSerializer):
project = ProjectSerializer(read_only=True, required=False)
image = Base64ImageField(max_length=None, use_url=False)
result = Base64ImageField(max_length=None, use_url=False, required=False)
class Meta:
model = Image
class ProjectImagesViewSet(viewsets.ViewSet):
queryset = Image.objects.select_related('project').all()
serializer_class = ImageSerializer
def list(self, request, project_pk=None):
queryset = self.queryset.filter(project__name=project_pk)
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
def update(self, request, pk=None, project_pk=None):
print(request.data['result'])
def partial_update(self, request, *args, **kwargs):
instance = self.queryset.get(pk=kwargs.get('pk'))
serializer = self.serializer_class(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)