自定义DRF列表功能不返回某些dict键/值对

时间:2017-08-17 21:56:49

标签: python django django-rest-framework

我正在尝试用自定义的方式替换Django REST Framework视图集中的标准列表函数,但是丢失了计数,前一个,下一个参数。如果没有覆盖,list函数将返回以下内容:

{
    "count": 3,
    "next": null,
    "previous": null,
    "results": [...]
}

当我覆盖该函数时,我只获得结果列表,而不是带有count,next,previous等的更高级别的dict。

此处缺少哪些功能可以启用该功能?

def list(self, request):
    loc = Location.objects.filter(user=request.user).latest('timestamp')
    nearby = loc.get_near()  # returns a list with dicts that contain user and dist

    nearby_users = [n['user'] for n in nearby]  # gets a list of users

    serializer = self.get_serializer(nearby_users, many=True)

    return Response(serializer.data)

1 个答案:

答案 0 :(得分:1)

您可以添加分页

def list(self, request):
    loc = Location.objects.filter(user=request.user).latest('timestamp')
    nearby = loc.get_near()  # returns a list with dicts that contain user and dist

    nearby_users = [n['user'] for n in nearby]  # gets a list of users

    # start pagination
    page = self.paginate_queryset(nearby_users)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
    # end pagination

    serializer = self.get_serializer(nearby_users, many=True)

    return Response(serializer.data)

第39行的超级mixins中的详细信息