[Fixed]-Create or Update (with PUT) in Django Rest Framework

13πŸ‘

βœ…

I ended up overriding the get_object() method in my ModelViewSet:

class ResourceViewSet(viewsets.ModelViewSet):
    """
    This endpoint provides `create`, `retrieve`, `update` and `destroy` actions.
    """
    queryset = Resource.objects.all()
    serializer_class = ResourceSerializer

    def get_object(self):
        if self.request.method == 'PUT':
            resource = Resource.objects.filter(id=self.kwargs.get('pk')).first()
            if resource:
                return resource
            else:
                return Resource(id=self.kwargs.get('pk'))
        else:
            return super(ResourceViewSet, self).get_object()

Perhaps there’s a more elegant way of doing this?

Leave a comment