Django Rest Framework序列化嵌套数据

时间:2017-12-22 02:58:17

标签: python django serialization django-rest-framework drf-queryset

我正在尝试序列化此序列化程序中的数据,但我总是得到输出{}

这是我的序列化程序:

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)

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

1 个答案:

答案 0 :(得分:0)

class RelationshipSerializer(serializers.ModelSerializer):

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

views.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)