Search code examples
djangoapidjango-rest-frameworkdjango-viewsdjango-annotate

annotate an extra field but show just once in api response in django rest


I have to add an extra field using annotate in the get api. The field is something like count of a field of all the objects, not a particular object. And I want it to appear just once in the response of get api. If I use annotate, it appears on all the objects response. How can it be achieved??

My model:

class Package(models.Model):
    location = models.CharField()
    bought_times = models.IntegerField(default=0)
    /....................../

Now if I use annotate something like this:

qs = Package.objects.filter(....).annotate(whole_bought_counts=Sum("bought_times") or some logic)

In the response it will come like:

{
id = 1,
localtion = Paris,
bought_times = 22,
whole_bought_counts =72,
}
{
id = 1,
localtion = Miami,
bought_times = 16,
whole_bought_counts =72,
}
id = 1,
localtion = Switzerland,
bought_times = 24,
whole_bought_counts =72,
}

I need the whole_bought_counts to appear just to appear once, because the count is used for the dashboard info only. Appearing several times will make it appear 100+ times which makes the api quite slow. isnt it??


Solution

  • Additional data can be added to response of a viewset. E.g.

    class PackageViewSet(ModelViewSet):
    
       model = Package
        serializer_class = PackageSerialzer
        queryset = Package.objects.all()
    
        def get_queryset(self):
            qs = Package.objects.filter(...) # Whatever you want your qs to be
            return qs
    
        def list(self, request):
            queryset = self.get_queryset()
            serializer = self.serializer_class(queryset, many=True)
    
            addional_data = {
                'my_data': ... # Any data, from your queryset or else
            }
            
            return Response([addional_data, serializer.data])