You cannot call save() after accessing serializer.data in Django Seriliazer

YOU CANNOT CALL `.SAVE()` AFTER ACCESSING `SERIALIZER.DATA`.IF YOU NEED TO ACCESS DATA BEFORE COMMITTING TO THE DATABASE

As the above error says, “If you need to access data before committing to the database then inspect ‘serializer.validated_data’ instead.

Written code:

serializerdata = serializers.CreateSerializer(data=request.data)
if serializerdata.is_valid():
    user_id = serializerdata.data.get('user_id')
    if user_id==2:
        serializerdata.save(i_created_by=request.user)
        return JsonResponse({"message": "success"}) 
    else:
        return JsonResponse({"message": "user invalid"})    
else:
    return JsonResponse({"message": "error"}) 

Solution: we can call this to access the data, like:-

user_id = serializerdata.validated_data.get('user_id')
serializerdata = serializers.CreateSerializer(data=request.data)
if serializerdata.is_valid():
    user_id = serializerdata.validated_data.get('user_id')
    if user_id==2:
        serializerdata.save(i_created_by=request.user)
        return JsonResponse({"message": "success"}) 
    else:
        return JsonResponse({"message": "user invalid"})    
else:
    return JsonResponse({"message": "error"}) 

Leave a Comment