0

I've a table Orders which contains ID, store_name, order_date, ..... I want to create an endpoint which returns me the JSON which consists of Count of Orders from all the Stores. Something as follows:

[{store_name: 'Target', count: 10}, {store_name: 'Walmart', count: 20}, {store_name: 'Costco', count: 5}]

The query I wrote is:

queryset = Stores.objects.all().values('store_name').annotate(total=Count('store_name'))

When I print queryset, I'm getting what I need as mentioned above. But when I serialize the data, I get the following:

[{store_name: 'Target'}, {store_name: 'Walmart'}, {store_name: 'Costco'}]

Not sure what am I doing wrong.. I've included my code. (I'm not including import statements)

serializer.py

class StoresSerializer(ModelSerializer):
    class Meta:
        model = Stores
        exclude = ['order_date',]

views.py

class StoresViewSet(ModelViewSet):
    queryset = Stores.objects.all().values('store_name').annotate(total=Count('store_name'))
    serializer_class = StoresSerializer

What am I missing?

Shrikant Kakani
  • 1,511
  • 2
  • 17
  • 37
  • Check that question http://stackoverflow.com/questions/18434425/how-to-add-annotate-data-in-django-rest-framework-queryset-responses – Ivan Semochkin Jan 17 '17 at 11:33

1 Answers1

0

Using one old topic it would go as follows

models.py (simplified version just to demonstrate the idea)

class Store(models.Model):
    name = models.CharField(max_length=100)

class Order(models.Model):
    store_name = models.ForeignKey(Store)
    order_date = models.DateTimeField(auto_now_add=True)

serializer.py

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import Store

class StoresSerializer(ModelSerializer):
    orders = serializers.IntegerField()

    class Meta:
        model = Store
        fields = ('name', 'orders')

views.py

class StoresViewSet(viewsets.ModelViewSet):
    queryset = Store.objects.all().values('name').annotate(orders=Count('order'))
    serializer_class = StoresSerializer
Community
  • 1
  • 1