【问题标题】:add a single data to serializer in django在 django 中将单个数据添加到序列化程序
【发布时间】:2022-02-08 23:06:42
【问题描述】:

我正在编写一个列出用户关注者的 API。我还想发送此 API 中的关注者总数。但 totalFollower 字段不断重复。我只想发送一次。像这样:

[
totalFollower:2
followers:
{
    {
        "following": "gizli_takip",
    },
    {
        "following": "herkeseacikvetakip",
    }
}]

我的序列化器

class SerializerUserFollowings(serializers.ModelSerializer):
following = serializers.CharField(source="follower.username")

totalFollower = serializers.ReadOnlyField()
class Meta:
    model  = ModelFollower
    fields = ("following","totalFollower")

【问题讨论】:

标签: python django django-models django-rest-framework django-serializer


【解决方案1】:

你有几个选择:

在您的视图上使用DRF paginator,这将在响应正文中提供count

from rest_framework.pagination import PageNumberPagination

class YourView(...):
    pagination_class = PageNumberPagination
    ...

或者,如果您使用的是视图集或类似 ListAPIView 的东西,您可以将特定数据添加到列表函数的响应中:

class YourView(ListAPIView):

    def get_queryset(self):
        return <some query for filtering follows by user>
    
    def list(self, request, *args, **kwargs):
        response = super().list(request, args, kwargs)
        response.data["count"] = self.get_queryset().count()
        return response

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2015-12-20
    相关资源
    最近更新 更多