Home > OS >  add a single data to serializer in django
add a single data to serializer in django

Time:02-08

enter image description here

I'm writing an API where the user's followers are listed.I also want to send the total number of followers in this API.But the totalFollower field keeps repeating.I only want it sent once. Like that:

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

MY serializer

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

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

CodePudding user response:

You have a couple of options:

Use a DRF paginator on your view, which will give a count in the response body:

from rest_framework.pagination import PageNumberPagination

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

Alternatively if you are using a viewset or something similar like ListAPIView you can add the specific data into the response for the list function:

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
  •  Tags:  
  • Related