我正在尝试编写一个序列化程序,它返回一个友谊对象,包括所有的friendship_creator和friendship_friend字段(名字,姓氏,电子邮件),而不只是ids。
用户模型是默认的auth.user模型,友谊模型如下所示:
class Friendship(models.Model):
creator = models.ForeignKey('auth.user', related_name = 'friendship_creator')
friend = models.ForeignKey('auth.user', related_name = 'friendship_friend')
status = models.IntegerField()
created = models.DateTimeField(auto_now_add = True)
serializers.py
class FriendshipSerializer(serializers.ModelSerializer):
class Meta:
model = Friendship
当前回复对象:
{
"id": 2,
"status": 2,
"created": "2015-05-03T17:33:05.027652Z",
"creator": 3,
"friend": 4
}
我希望“创建者”和“朋友”包含整个用户对象
答案 0 :(得分:0)
您需要为User模型实现序列化程序。说UserSerializer:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
然后在FriendshipSerializer上明确声明'creator'和'friend'属性,分配UserSerializer的实例:
class FriendshipSerializer(serializers.ModelSerializer):
creator = UserSerializer()
friend = UserSerializer()
class Meta:
model = Friendship
在the docs中相当清楚。