Search code examples
djangorestdjango-modelsdjango-rest-frameworkput

How to use PUT method to create object in Django


How to use PUT method for creating an object on particular id if no object is available on that id in Django Rest Framework?


Solution

  • You can try update_or_create()

    e.g:

    class YourAPIView(APIView):
    
        def put(self, request, **kwargs):
            serializer = YourSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            obj, created = YourModel.objects.update_or_create(
            id=kwargs['id'],
            defaults=serializer.validated_data)
            return Response()