1

我试图在这个序列化器中序列化数据,但我总是得到输出{}

这是我的序列化程序:

class RelationshipSerializer(serializers.ModelSerializer):

    user = UserSerializer(read_only=True)
    related_user = UserSerializer(read_only=True)

    class Meta:
        model = models.Relationship
        fields = (
            'user',
            'related_user',
        )

这是我的看法:

related_user_id = body["related_user"]
related_user = models.User.objects.get(id=related_user_id)

user = self.get_object()

user_serializer = serializers.UserSerializer(user).data
related_user_serializer = serializers.UserSerializer(related_user).data

# user_serializer and related_user_serializer return valid data.

data = {"user": user_serializer, "related_user": related_user_serializer}

serializer = serializers.RelationshipSerializer(data=data)

serializer.is_valid() # valid

return Response(serializer.data)

related_user从发布请求中获取 id,然后获取实际对象的查询集,并且user是在 url: 中传递的 id user/{1}/。然后我序列化每个用户并创建一个字典来传递给RelationshipSerializer. 序列化程序返回有效但响应是{},我做错了什么?

4

1 回答 1

0
class RelationshipSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Relationship
        fields = (
            'user',
            'related_user',
        )  

视图.py

user = self.get_object()
data = {"user": user.id, "related_user": request.data["related_user"]}

serializer = serializers.RelationshipSerializer(data=data)
if serializer.is_vaild():
    serializer.save()
return Response(serializer.data)
于 2017-12-22T03:15:02.830 回答