DRF: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list

ViewSetの querysetorder_by を明示的に指定すること

I see. Django REST framework also supports pagination for large result sets, but you need to specify a default pagination class and a page size in your settings.py file¹. Alternatively, you can set the pagination_class attribute for each viewset individually⁴. However, you still need to order your queryset by some field, otherwise you will get the same warning as before²³. You can use the order_by method on your queryset or the ordering attribute on your viewset¹. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# views.py
from rest_framework import viewsets
from .models import Profile
from .serializers import ProfileSerializer

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all().order_by('id')
    serializer_class = ProfileSerializer

ソース: Bing との会話 2023/4/29