From 0f035927118182a9e243194d7c1eb59b4e6e7e4a Mon Sep 17 00:00:00 2001 From: ddelange <14880945+ddelange@users.noreply.github.com> Date: Mon, 20 Mar 2023 08:27:09 +0100 Subject: [PATCH] Ensure CursorPagination respects nulls in the ordering field --- rest_framework/pagination.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index f5c5b913b..87926b381 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -10,6 +10,7 @@ from urllib import parse from django.core.paginator import InvalidPage from django.core.paginator import Paginator as DjangoPaginator +from django.db.models import Q from django.template import loader from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ @@ -631,7 +632,10 @@ class CursorPagination(BasePagination): else: kwargs = {order_attr + '__gt': current_position} - queryset = queryset.filter(**kwargs) + # If some records contain a null for the ordering field, don't lose them. + filter_query = Q(**kwargs) | Q(**{order_attr + '__isnull': True}) + + queryset = queryset.filter(filter_query) # If we have an offset cursor then offset the entire page by that amount. # We also always fetch an extra item in order to determine if there is a