I wrote a site on django. And I noticed that User.objects.all() gives me users out of order.

That is, for example, I have a user with id=1 Sasha, there is with id=2 Pasha, with id=3 Masha, with id=4 Dasha. And User.objects.all() gives me in the order of 3, 2, 1, 4 instead of 1, 2, 3, 4. The question is why? What criteria does django sort out of the box?

PS: I know about order_by and that I can override the default sort field in the Meta class. I’m wondering just how it does it directly User.objects.all()

    1 answer 1

    This is not Django sorts them by some criterion, it is he who gets them from the DBMS. In accordance with the SQL standard, if the query does not explicitly define a sort, the order of the results can be arbitrary.

    If there is a desire to define the default sorting, this can be done in the model meta-class:

     class SomeModel(models.Model): some_field = models... another_field = models... class Meta: ordering = ['some_field'] 
    • Clear, I will know. An interesting SQL standard ... - Alexander