我想让用户能够在 Django Rest API 中使用 PUT 请求仅更新某些属性。举个例子,如果我有以下模型并且只希望用户能够更新他们的名字和姓氏,我将如何去做呢?
models.py:
class User(models.Model):
email = models.EmailField('email address', unique = True)
first_name = models.TextField(max_length = 10)
last_name = models.TextField(max_length = 20)
(请注意,他们不应该能够更改自动设置的“id”字段)
serializers.py:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'email', 'first_name', 'last_name']
views.py:
class SingleUser(APIView):
def put(self, request, user_id):
user = User.objects.get(pk = user_id)
serializer = UserEditSerializer(user, data = request.data)
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)
强制用户只能更改这些属性的子集的最佳方法是什么?
慕少森
PIPIONE
白衣非少年
相关分类