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?

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.