我很困惑在Django Rest Framework中使用扩展用户模型创建一个Patch方法。希望你们的帮助。
我的扩展用户模型:
class Profile(models.Model):
user = models.OneToOneField(User, unique=True)
bio = models.CharField
我的序列化程序:
class UserEditSerializer(ModelSerializer):
bio = serializers.CharField(source='profile.bio')
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'bio'
]
我的观看次数:
class UserUpdateAPIView(ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserEditSerializer
@detail_route(methods=['PATCH'])
def edit(self, request):
user_obj = User.objects.get(user__id=request.user.id)
print(user_obj)
serializer = UserEditSerializer(user_obj, data=request.data, partial=True)
print(request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(status=status.HTTP_400_BAD_REQUEST)
使用POSTMAN发送的数据(json)
{“email”:“231@sda.com”,“个人资料”:{“bio”:“无法发送请求”}}
错误:
Profile.Bio cant response true data
照片:
答案 0 :(得分:1)
UserEditSerializer的模型是Profile
类。但是您尝试传递对象User
实例。您需要更改序列化程序类:
class UserEditSerializer(ModelSerializer):
bio = serializers.CharField(source='profile.bio')
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'bio',
]
或查看:
@detail_route(methods=['PATCH'])
def edit(self, request):
user_obj = Profile.objects.get(user__id=request.user.id)
serializer = UserEditSerializer(user_obj, data=request.data, partial=True)
<强> UPD 强>
要使嵌套关系可写,您需要覆盖序列化程序的create
和update
方法,请参阅doc中的详细信息。
例如:
class UserEditSerializer(ModelSerializer):
bio = serializers.CharField(source='profile.bio')
class Meta:
model = User
fields = [
'username',
'email',
'first_name',
'last_name',
'bio',
]
def update(self, instance, validated_data):
profile = validated_data.pop('profile')
instance = super().update(instance, validated_data)
instance.profile.bio = profile.get('bio', instance.profile.bio)
instance.profile.save()
return instance
您还需要发布此类{ "email": "231@sda.com", "bio": "Cant send request" }
的数据。