我试图在这个序列化器中序列化数据,但我总是得到输出{}
这是我的序列化程序:
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
. 序列化程序返回有效但响应是{}
,我做错了什么?