如何返回帖子作者ID和用户名而不是仅返回DjangoREST中的ID

时间:2019-09-21 12:59:16

标签: django django-rest-framework

当我向/ api / posts /发出GET请求时,我仅收到作者ID,但我也希望作者用户名显示它。我该怎么办?

我希望响应是这样的:

[
  {
     // all other stuff
     author: {
       id: 1,
       username: "foo"
     }
  }
]

这是我的“帖子”视图集:

class PostViewSet(viewsets.ModelViewSet):
    """Handle CRUD for Posts"""
    serializer_class = serializers.PostSerializer
    authentication_classes = (TokenAuthentication,)
    queryset = Post.objects.all()

    def perform_create(self, serializer):
        """Set author to current user"""
        serializer.save(user=self.request.user)

这就是我的回应:

[
    {
        "id": 1,
        "title": "Welcome!",
        "description": "Welcome test!",
        "created_at": "2019-09-21T01:05:58.170330Z",
        "author": 1,
        "community": 2
    }
]

我也想对社区做同样的事情,但我想我会从作者解决方案中找出答案。

2 个答案:

答案 0 :(得分:1)

您可以覆盖序列化程序的to_representation()方法:

class PostSerializer:
    """ Your code here"""

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['author'] = {"id": instance.author.id, "username": instance.author.username}
        return ret

答案 1 :(得分:1)

使用Nested Serializer


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'username')
        model = AuthorModel


class PostSerializer(...):
    author = AuthorSerializer()
    # other things

更新

在这种情况下,我们必须覆盖 to_representation 方法。我已经在这里回答了,DRF: Simple foreign key assignment with nested serializers?

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'username')
        model = AuthorModel


class PostSerializer(...):
    # author = AuthorSerializer() # no need of this here
    # other things
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation["author"] = AuthorSerializer(instance.author).data
        return representation