def update 创建一个新的但不更新 - Django

def update creates a new one but does not update - Django

我有一种方法可以在我的数据库中创建一个新项目,而且效果很好。但是更新的类似方法是创建一个新项目而不是更新,如果我强制传入“数据”id,它会抱怨这个id已经存在...

我的代码:

class EventsAttachViewSet(
    mixins.ListModelMixin,
    mixins.CreateModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet
):
    permission_classes = [permissions.AllowAny]
    queryset = EventAttachment.objects.all()
    serializer_class = EventAttachmentSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        self.perform_update(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

这里需要传递对象的实例进行更新。


def update(self, request, *args, **kwargs):
        <b>instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data)</b>
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        self.perform_update(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

</pre>