DEV Community

DoriDoro
DoriDoro

Posted on

Django REST Framework warning: `UnorderedObjectListWarning`

While creating a basic Django REST framework project with several models and the implementation of pagination, I faced this warning in terminal:

UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list

I used the implementation of the DRF website the point: PageNumberPagination

I copied this into my settings.py file inside my project:

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 100
}
Enter fullscreen mode Exit fullscreen mode

and the above warning was popping up in terminal.

The explanation on the DRF website is, you have to order the queryset.

DRF expects an ordering of ["-created"].

The names of my attributes for the creation in my models where different, "created_time" and in the User model of Django the timestamp attribute is "date_joined". So, I had to come up with something.



There are two possible solutions:

1) add in the model class the ordering:

# models.py

from django.db import models

class Project(models.Model):
    created_time = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100)
    description = models.TextField()
    author = models.ForeignKey()

    class Meta:
        ordering = ["created_time"]
Enter fullscreen mode Exit fullscreen mode

the important part is the ordering = ["created_time"]. With this line of code you order the entries in your database by the create date and time.

2) add the .order_by() method to the queryset in the view:

# views.py

class ProjectViewSet(viewsets.ModelViewSet):

    def get_queryset(self):
        # use order_by to avoid the warning for the pagination
        return Project.objects.filter(author=self.request.user).order_by(
            "created_time"
        )
Enter fullscreen mode Exit fullscreen mode

You order the queryset by the timestamp when the project was created .order_by("created_time").

Top comments (0)