在 Django 中将单个数据添加到序列化程序

add a single data to serializer in django

我正在写一个 API 其中用户的关注者是 listed.I 还想发送此 API.But 中的关注者总数 totalFollower 字段保持 repeating.I只希望发送一次。像那样:

[
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")

您有两个选择:

在您的视图中使用 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