Django rest框架:不返回数组,而是返回id为key的对象列表

时间:2016-10-05 15:26:53

标签: django serialization django-rest-framework

Django rest框架在API端点返回以下输出

  [
    {
        "id": "QFELD_2.3.2.QF1",
        "siteuxid": "VBKM02_Abschlusstest",
        "section": 2,
        "maxpoints": 4,
        "intest": true,
        "uxid": "KA0",
        "points": 0,
        "value": 0,
        "rawinput": "",
        "state": 3
    },
    {
        "id": "QFELD_2.3.2.QF2",
        "siteuxid": "VBKM02_Abschlusstest",
        "section": 2,
        "maxpoints": 4,
        "intest": true,
        "uxid": "KA1",
        "points": 0,
        "value": 0,
        "rawinput": "",
        "state": 3
    }, 
...

是否可以以列表对象格式返回数据,如:

  {
    "QFELD_2.3.2.QF1" : {
        "siteuxid": "VBKM02",
        "section": 2,
        "maxpoints": 4,
        "intest": true,
        "uxid": "KA0",
        "points": 0,
        "value": 0,
        "rawinput": "",
        "state": 3
    },
    "QFELD_2.3.2.QF2" : {
        "siteuxid": "VBKM02",
        "section": 2,
        "maxpoints": 4,
        "intest": true,
        "uxid": "KA1",
        "points": 0,
        "value": 0,
        "rawinput": "",
        "state": 3
    },
...

我的序列化器是:

class ScoreSerializer(serializers.ModelSerializer):
    id = serializers.CharField(required=False, allow_blank=True, max_length=100, source='q_id')
    class Meta:
        model = Score
        fields = ('id', 'siteuxid', 'section', 'maxpoints', 'intest', 'uxid', 'points', 'value', 'rawinput', 'state')

观点是:

class ScoreViewSet(viewsets.ModelViewSet):

    serializer_class = ScoreSerializer

1 个答案:

答案 0 :(得分:5)

ListMixin代码是开始使用的好地方。您应该获得序列化程序的结果并根据需要进行转换。

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            # Might need to change this not to transform all the data
            data = {i['id']: i for i in serializer.data}
            return self.get_paginated_response(data)

        serializer = self.get_serializer(queryset, many=True)
        data = {i['id']: i for i in serializer.data}
        return Response(data)