我正在尝试更新我的Profile
模型上的information
字段。端点正在正确地接收数据,但序列化器似乎没有获得数据。我不明白为什么,我的尝试都没有成功。
模型:
class Profile(models.Model):
id = models.UUIDField(uuid.uuid4, primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
information = models.JSONField(null=True)
def __str__(self):
return f'{self.user} Profile'
端点:
class ProfileView(viewsets.ModelViewSet):
serializer_class = ProfileSerializer
queryset = Profile.objects.all()
def update(self, request, *args, **kwargs):
# Retrieve the user's profile
profile = Profile.objects.get(user=request.user)
# Update the information field with the data from the request
data = request.data
print(data) # This prints the data correctly
serializer = self.get_serializer(profile, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
序列化器:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ["user", "information"]
def validate(self, attrs):
print(attrs) # this prints an empty OrderedDict
return super().validate(attrs)
def update(self, instance, validated_data):
print(validated_data) # This prints an empty dictionary
# Update the information field with the data from the request
instance.information = validated_data["information"]
instance.save()
return instance
通过请求体传递的数据:
JSON.stringify({"information": {"name": "xxx", "birthday": "xxx}})
数据怎么可能就这么消失了?任何帮助都是非常感谢的
好吧,我是一个白痴,忘记在我的请求头设置"Content-Type": "application/json"
。希望它能节省别人的时间。