DRF: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list
ViewSetの queryset で order_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:
# 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
- (1) Pagination - Django REST framework. https://www.django-rest-framework.org/api-guide/pagination/.
- (2) python - Django Rest Framework: turn on pagination on a … https://stackoverflow.com/questions/31785966/django-rest-framework-turn-on-pagination-on-a-viewset-like-modelviewset-pagina.
- (3) Python Django Rest Framework UnorderedObjectListWarning. https://stackoverflow.com/questions/44033670/python-django-rest-framework-unorderedobjectlistwarning.
- (4) Solved: Pagination may yield inconsistent results with an …
https://lynxbee.com/solved-pagination-may-yield-inconsistent-results-with-an-unordered-object-list/. - (5) UnorderedObjectListWarning: Pagination may yield … https://torajirousan.hatenadiary.jp/entry/2019/07/10/230552.