【发布时间】:2023-03-17 19:06:01
【问题描述】:
我的 UserProfile 模型包含 phone、profile_photo 和 Django 默认用户模型的一些字段,例如 first_name、last_name、email,我正在尝试更新其中一些字段。
models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, verbose_name="User")
phone = models.CharField(max_length=16, verbose_name="Phone")
profile_photo = models.ImageField(null=True, blank=True, upload_to=user_directory_path, verbose_name="Profile Photo")
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('url', 'first_name', 'last_name', 'email')
class UserProfileSerializer(serializers.ModelSerializer):
user = UserSerializer(partial=True)
class Meta:
model = UserProfile
fields = '__all__'
def create(self, validated_data):
user_profile = UserProfile.objects.create(**validated_data)
return user_profile
views.py
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
authentication_classes = (TokenAuthentication,)
@detail_route(methods=['PATCH'], url_path='update-partial')
def user_profile_update_partial(self, request, pk=None):
profile = UserProfile.objects.get(id=pk)
serializer = self.get_serializer(profile, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
如果我使用此@detail_route 发送profile_photo、phone、first_name 或last_name 数据,我只能更新电话和profile_photo 字段。当profile_photo 数据未发送时也会出现 Bad Request 错误。
如何使用PATCH 方法实现partial_update?
【问题讨论】:
标签: python django django-models django-rest-framework django-serializer