djangodjango-rest-frameworkpaginationdrf-queryset

PageNumberPagination and a queryset without fixed order


According to the documentation, nothing special is required to enable pagination when using a class inheriting from GenericAPIView.

I've looked in the code of django and django rest framework and the ViewSet queryset doesn't seem ordered. The pagination only adds the SQL keywords LIMIT and OFFSET to the query.

What I don't understand is how is handled a queryset that doesn't have a deterministic order ? Why the documentation doesn't say to add a .order_by() statement at the end of the ViewSet queryset ?


Solution

  • Ordering is required to have pagination working properly. Without that you can have few rows repeated across different pages and few missing. It is also mentioned in django docs:

    For consistent pagination, QuerySets should be ordered, e.g. with an order_by() clause or with a default ordering on the model.

    https://docs.djangoproject.com/en/2.2/topics/pagination/#required-arguments

    It is also worth to read this article about default ordering: https://learn.microsoft.com/pl-pl/archive/blogs/conor_cunningham_msft/no-seatbelt-expecting-order-without-order-by