3 回答
TA贡献2019条经验 获得超9个赞
您可以在序列化器上设置只读字段:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'email', 'first_name', 'last_name']
read_only_fields = ['id', 'email']
确保在 put 函数中将序列化器设置为部分:
serializer = UserEditSerializer(user, data = request.data, partial=True)
您还可以完全省略序列化程序中的字段,这将使用户根本无法使用这些字段。
TA贡献1829条经验 获得超9个赞
创建一个单独的序列化器并使用它
# serializers.py
class UserPutSerializer(serializers.ModelSerializer): # new serializer class
class Meta:
model = User
fields = ['first_name', 'last_name'] # define required fields
#views.py
class SingleUser(APIView):
def put(self, request, user_id):
user = User.objects.get(pk=user_id)
serializer = UserPutSerializer(user, data=request.data) # use new serializer here
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
添加回答
举报