Skip to content

Commit e8b2300

Browse files
committed
Optimize get_count of the offset paginator
1 parent 4911f49 commit e8b2300

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

styleguide_example/api/pagination.py

+17
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,23 @@ class LimitOffsetPagination(_LimitOffsetPagination):
2424
default_limit = 10
2525
max_limit = 50
2626

27+
def get_count(self, queryset) -> int:
28+
"""
29+
Determine an object count, supporting either querysets or regular lists.
30+
"""
31+
try:
32+
# We remove the prefetches in order to optimize the queryset
33+
clone = queryset._clone() # type: ignore
34+
return (
35+
clone.prefetch_related(None)
36+
.select_related(None)
37+
.only("pk")
38+
.values_list("pk")
39+
.count()
40+
)
41+
except (AttributeError, TypeError):
42+
return len(queryset)
43+
2744
def get_paginated_data(self, data):
2845
return OrderedDict([
2946
('limit', self.limit),

0 commit comments

Comments
 (0)