具有用户表(具有字段ID,名称)和注释表(注释,CreatedBy(整数)-这是用户ID)。
我该如何编写一个序列化程序来获取用户列表,该列表应包含每个用户创建的注释数组。
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = ('id','name')
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = UserComments
fields = ('id','comment','created_by')
期望以下输出:
[
{
"id":1,
"name":"Tony",
"comments":[
{
"id":1,
"comment":"This is a test comment"
},
{
"id":2,
"comment":"This is a test comment2"
}
]
},
{
"id":2,
"name":"Alaric",
"comments":[
{
"id":3,
"comment":"This is a test comment3"
},
{
"id":4,
"comment":"This is a test comment4"
}
]
}
]
答案 0 :(得分:1)
最好的方法是使用ForeignKey关系和嵌套的序列化程序,但是如果由于某些原因您不能在 UserComments 和 Users 之间声明外键关系,您可以使用 SerializerMethodField s:
class UserSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField()
class Meta:
model = Users
fields = ('id','name', 'comments')
def get_comments(self, obj):
return CommentSerializer(UserComments.objects.filter(created_by=obj.id), many=True).data