Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django : Serializer validation prevents my code from updating an existing object

I have a Django project that get some user data and store them in a database.
I want my function to handle both Create and Update with the same method, so I created a view that inherit from UpdateAPIView

class UserList(generics.UpdateAPIView):
    queryset = RawUser.objects.all()
    serializer_class = RawUserSerializer
    
    def put(self, request, *args, **kwargs):
        raw_user_serializer: RawUserSerializer = self.get_serializer(data=request.data)
        raw_user_serializer.is_valid(raise_exception=True)  # Fail when user already exists
        raw_user: RawUser = RawUser(**raw_user_serializer.validated_data)

        // Some custom computing

        # Create or update raw_user
        self.perform_update(raw_user_serializer)

        return JsonResponse({'user_id':raw_user.id}, status = 201) 

class UserDetail(generics.RetrieveAPIView):
    queryset = RawUser.objects.all()
    serializer_class = RawUserSerializer

I think that the use of a UpdateAPIView and the function perform_update() is good. It works well when the user doesn’t exist already, but when I try to create a new user with the same primary key, I get : Bad Request: /api/profiling/users/, with the following response :

{
    "id": [
        "raw user with this id already exists."
    ]
}

It look like it fails on raw_user_serializer.is_valid(raise_exception=True) instruction. How can I solve my issue ? (while keeping the validation of my object)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The serializer thinks you want to create a new object. You should pass the instance you want to (completely) update:

class UserList(generics.UpdateAPIView):
    queryset = RawUser.objects.all()
    serializer_class = RawUserSerializer

    def put(self, request, *args, **kwargs):
        instance = self.get_object()
        raw_user_serializer: RawUserSerializer = self.get_serializer(
            instance, data=request.data, partial=False
        )
        raw_user_serializer.is_valid(
            raise_exception=True
        )  # Fail when user already exists
        raw_user = raw_user_serializer.update(self.instance, validated_data)

        # some computing…

        self.perform_update(raw_user_serializer)

        return JsonResponse({'user_id': raw_user.id}, status=201)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading