DRF - 从QuerySet输出格式化串行器的输出

时间:2015-09-21 16:40:53

标签: django serialization django-rest-framework

我在第一时间使用Django Rest Framework,现在我试图获得这样的输出:

{
  "qty": 5,
  "total": 20,
  "items": [
     {
       "id": 1,
       "name": "name_1"
     },
     {
       "id": 2,
       "name": "name_2"
     }
  ]
}
来自Serializer的

。上面输出中的结果数据来自查询集。我想在序列化程序类中使用queryset。如果没有在序列化程序中进行查询,我无法获得我想要的结果:

class ResSerializer(serializers.Serializer):

    qty = serializers.SerializerMethodField()
    items = serializers.SerializerMethodField()
    total = serializers.SerializerMethodField()

    def get_qty(self, obj):
        try:
            return Model.objects.filter(...)\
                                .aggregate(qty=Sum('job__long'))\
                                .get('qty')
        except KeyError:
            return 0

    def get_items(self, obj):
        print 'testing'

    def get_total(self, obj):
        return 0

    class Meta:
        fields = ('qty', 'items', 'total')

我正在调用Serializer:

queryset = Model.objects.filter(...)
serialized = ResSerializer(queryset, many=False, context={'current_user': request.user})

但这不符合我的要求。任何消化?感谢。

更新

这是我查询的模型:

class Intermediate(models.Model):

    partner = models.ForeignKey('partner.Partner')
    job = models.ForeignKey(Job)
    joined_at = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    status = models.SmallIntegerField(default=STATUS_ACCEPTED)
    reason_index = models.SmallIntegerField('Cancel reason', default=REASON_3)
    start_time = models.TimeField(null=True)
    end_time = models.TimeField(null=True)
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)

以下是观点:

class ResView(CustomAPIView):

    authentication_classes = (CustomTokenAuthentication, )
    # permission_classes = (PartnerAuthenticatedOnly, )  # Uncomment this on server

    def post(self, request, *args, **kwargs):
        try:
            queryset = JobPartner.objects.filter(...)
            serialized = ResSerializer(queryset, many=False, context={'current_user': request.user})
            response_success_object(self.response_dic, serialized.data)
            return Response(self.response_dic)

        except Exception, e:
            print e

1 个答案:

答案 0 :(得分:1)

要获得items代表,您可以使用ItemsSerializer来提供包含idname的序列化数据。

class ItemsSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel # specify your model
        fields = ('id', 'name') # return these 2 fields in the representation

处理多个实例时,此序列化程序将以下面的方式返回序列化数据。

[
     {
       "id": 1,
       "name": "name_1"
     },
     {
       "id": 2,
       "name": "name_2"
     }
  ]

现在,qtytotal字段取决于查询集,而不是查询集的特定对象,如果在视图中单独计算它们会更好。然后创建一个包含字段itemsqtytotal的字典,并将其作为回复返回。

class ResView(CustomAPIView):

    authentication_classes = (CustomTokenAuthentication, )
    # permission_classes = (PartnerAuthenticatedOnly, )  # Uncomment this on server

    def post(self, request, *args, **kwargs):
        try:
            queryset = JobPartner.objects.filter(...)
            qty = self.get_qty() # compute the value of qty
            total = self.get_total() # compute the value of total
            items_serializer = ItemsSerializer(queryset, many=True) 
            items = items_serializer.data # compute the value of items
            return_dict = { # prepare response data
                'qty' : qty,
                'total': total,
                'items': items 
            }
            return Response(return_dict) # return the response

        except Exception, e:
            print e