DjangoRestFramework:无法在JSON响应中返回计数

时间:2017-01-17 08:31:54

标签: python django-rest-framework django-1.9

我有一个表包含ID,store_name,order_date,.....我要创建一个端点,它返回JSON,其中包含来自所有商店的订单计数。如下:

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

我写的查询是:

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

当我打印查询集时,我得到了上面提到的我需要的东西。 但是当我序列化数据时,我得到以下结果:

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

不确定我做错了什么..我已经包含了我的代码。 (我不包括进口声明)

serializer.py

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

views.py

{{1}}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

使用one old topic它将如下

models.py(简化版只是为了演示这个想法)

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