Created
November 5, 2020 20:46
-
-
Save toast38coza/0e643b7af4a3a451927053b97e1846e0 to your computer and use it in GitHub Desktop.
Faceted pagination for Django Rest Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FacetedPagination(pagination.PageNumberPagination): | |
""" | |
If requested, will include facet information in the response | |
Example response | |
``` | |
{ | |
"links": { | |
"next": .., | |
"previous": .., | |
}, | |
"count": 10000, | |
"results": [..], | |
"facets": { | |
"color": {"red": 250, "green": 250, "blue": 500}, | |
"status": {"new": 250, "complete": 700, "in-progress": 50}, | |
.. | |
} | |
} | |
``` | |
""" | |
page_size = 10 | |
page_size_query_param = "page_size" | |
max_page_size = 1000 | |
def paginate_queryset(self, queryset, request, view=None): | |
from querytools.tools import group_by_and_annotate | |
facets = view.facet_fields | |
facet_data = {} | |
for facet in self.facet_fields: | |
facet_data[facet] = group_by_and_annotate(queryset, facet, "Count") | |
self.facet_data = facet_data | |
return super(FacetedPagination, self).paginate_queryset(queryset, request, view) | |
def get_paginated_response(self, data): | |
print("get response:") | |
return response.Response( | |
{ | |
"links": { | |
"next": self.get_next_link(), | |
"previous": self.get_previous_link(), | |
}, | |
"count": self.page.paginator.count, | |
"results": data, | |
"facets": self.facet_data, | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyView(views.ModelView): | |
... | |
facet_fields = ["color", "status"] | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment