如何实现APIView来获取需求数据?

时间:2018-08-09 07:24:23

标签: python django django-rest-framework

我有两个模型:

class TypeModel(models.Model):
    type = models.CharField(max_length=12)

class Amodel(models.Model):
    name = models.CharField(max_length=12)
    type = models.ForeignModel(to=TypeModel)
    in_use = models.BooleanField(default=False)

Amodel是主要模型,它具有一个引用TypeModel的type字段。

serializers.py中:

class AmodelSerializer(ModelSerializer):
    class Meta:
        model = Amodel
        fields = "__all__"


class TypeModelSerializer(ModelSerializer):
    class Meta:
        model = TypeModel
        fields = "__all__"

我的要求是像这样获取Amodel数据,应将其除以type,我要获取此类型数据:

[
  {
    "type": {
      name: 'type1' 
    },
   "count": {
      "used": 12,  # the in_use is `True`
      "unused": 24
    }
  },
  ...
]

计算已使用和未使用的计数。

    for amodel in amodel_qs:
        if amodel.in_use: used_count+=1 
        else: unused_count +=1 

0 个答案:

没有答案
相关问题