oliparcol
oliparcol

Reputation: 23

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 ?

Upvotes: 2

Views: 1537

Answers (2)

Kasikn77
Kasikn77

Reputation: 309

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

Upvotes: 0

hurturk
hurturk

Reputation: 5454

Queries without explicit order should be database specific and there is no guarantee you will get a sorted result set (unless django sorts by id as default), please see here for similar answer.

Upvotes: 0

Related Questions