gpt4 book ai didi

Django休息框架: Adding a custom field to a paginated ViewSet

转载 作者:行者123 更新时间:2023-12-02 08:35:20 25 4
gpt4 key购买 nike

我有一个分页结果集,因此响应返回如下:

{
"count": 944,
"next": "http://api.visitorlando.teeny/consumer/listings/?page=3",
"previous": "http://api.visitorlando.teeny/consumer/listings/",
"results": [
{...}]
}

我需要向响应添加另一个自定义字段,如下所示:

{
"count": 944,
"custom_field": "test",
"next": "http://api.visitorlando.teeny/consumer/listings/?page=3",
"previous": "http://api.visitorlando.teeny/consumer/listings/",
"results": [
{...}]
}

我在 ViewSet 中。我怎样才能做到这一点?

最佳答案

您可以定义自定义分页类:

class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
'count': self.page.paginator.count,
'results': data,
"custom_field": "test",
})


class YourListView(generics.ListAPIView):
pagination_class = CustomPagination

更多详情:custom-pagination

关于Django休息框架: Adding a custom field to a paginated ViewSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45446953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com