将项添加到ListAPIView

时间:2018-04-16 08:40:03

标签: django django-rest-framework

我有普通的ListAPIView,带有指定的模型和序列化程序类。我需要在列表末尾添加一个额外的项目。此项应手动创建(无查询集),并且应具有与其他项相同的结构。

4 个答案:

答案 0 :(得分:2)

您可以为此覆盖list方法:

from rest_framework.response import Response

class YoourView(generics.ListAPIView):

    def list(self, request):
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)

        # append serializer's data with some additional value
        response_list = serializer.data 
        response_list.append(some_value)
        return Response(response_list)

答案 1 :(得分:1)

试试这个,

from rest_framework import generics
from rest_framework.response import Response


class MyListView(generics.ListAPIView):
    serializer_class = MySerializer
    queryset = MyModel.objects.all()

    def list(self, request, *args, **kwargs):
        response_list = list(super().list(request, *args, **kwargs))
        custom_dict = {
            "key_1": "value 1",
            "key_2": "value 2"
        }
        response_list.append(custom_dict)
        return Response(data=response_list)

答案 2 :(得分:0)

我认为保留get_querysetfilter_querysetget_serializer函数会更好,以防您修改serializer_class而不是使用默认{{1} }}

serializer_class

答案 3 :(得分:0)

我建议您将实际负载与要传递的额外数据分开。这样一来,当您以后遍历那些冲突时,将有助于您避免很多冲突。

尝试一下:

class YourView(ListAPIView):
    queryset = YourModel.objects.all()
    serializer_class = YourSerializer

def list(self, request, args, **kwargs):
    serializer = self.get_serializer(self.get_queryset(), many=True)
    load = serializer.data
    newdict = {'your_new_data': 666}
    response_list = {'load': load, 'extra': newdict}
    return Response(response_list)