问题
I have a "next object" feature on my website but I use pagination. I would like add "ids" field that contains ids of all objects filtered and sorteded into the paginated response.
Everything that I tried returns only a list of current page ids.
class StandardResultsSetPagination(PageNumberPagination):
page_size = 20
page_size_query_param = 'page_size'
max_page_size = 20
def get_paginated_response(self, data, list_of_ids):
return Response(OrderedDict([
('count', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data),
('ids', list_of_ids)
]))
class RealestateViewSet(ModelViewSet):
...
pagination_class = StandardResultsSetPagination
def get_paginated_response(self, data, list_of_ids):
"""
Return a paginated style `Response` object for the given output data.
"""
assert self.paginator is not None
return self.paginator.get_paginated_response(data, list_of_ids)
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)
return self.get_paginated_response(serializer.data, list(queryset.values_list('id', flat=True)))
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
This returns a list of 20 ids instead of all filtered objects ids.
Do you know how to do that?
回答1:
you can subclass BaseFilterBackend
to filter the queryset (coming from get_queryset()
) by providing the ids , then appending the subclass to ModelViewSet.filter_backends
.
It's not clear about where your ids
comes from in your question (from URL parameters ? e.g. http://your_url?param1=value1
), but a quick example may be like this :
from rest_framework.filters import BaseFilterBackend
class LimitQsetFilter(BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
ids = [1,2,3,4]
queryset = queryset.filter(pk__in=ids)
return queryset
class RealestateViewSet(ModelViewSet):
...
filter_backends = [LimitQsetFilter,]
...
Then you will see filtered list of object instances on pagination.
来源:https://stackoverflow.com/questions/64610086/drf-paginated-response-append-list-of-all-ids