Issue
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)
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)
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.