I turned pagination on in Django Rest framework and it appears to be incredibly slow. Count looks like the culprit, and is taking hundreds of milliseconds to return each time due to the millions of rows in the tables.
I am using postgresql as the database. Is there any way to not count the rows and still use pagination? The performance was fine before this was enabled if I manually filtered the queryset.
The issue is, that the query used to count is the same potentially complex one as used to fetch the data. That's rather wasteful.
PageNumberPagination
uses Django's ownPaginator
internally.To make the query for the count simpler override the paginator class DRF uses:
If you are ok without count, next and previous links, Following custom class can be used.
Override the
get_paginated_response
method of your pagination class, and do not include the count. You can refer to the base implementation of thePageNumberPagination
class to see what you should return.Then in your
settings.py
, setDEFAULT_PAGINATION_CLASS
to your new pagination class.This approach is used in the example in the pagination docs.
Edit: from the comments below it sounds like this might not be enough to prevent the slow sql query, so you might need to override
paginate_queryset
as well.