Home > Mobile >  Django QuerySet .order_by() method
Django QuerySet .order_by() method

Time:11-30

I have this code down here and from my understanding order_by over writes the default behavior of the ordering option in the model’s Meta. see the documentation here https://docs.djangoproject.com/en/4.1/ref/models/querysets/#order-by

my question is what criteria does the order_by() in this case use to order the QuerySet if there are no fields provided? Does it make a difference having it there?

        order.discounts.filter(voucher_id=OuterRef("pk"))
        .order_by()
        .values("voucher_id")
        .annotate(Sum("amount"))
        .values("amount__sum")
    )

CodePudding user response:

Calling order_by() with no parameters removes all ordering from the queryset and results are returned in an unspecified order by the database

Docs

If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters

If a query doesn’t have an ordering specified, results are returned from the database in an unspecified order. A particular ordering is guaranteed only when ordering by a set of fields that uniquely identify each object in the results. For example, if a name field isn’t unique, ordering by it won’t guarantee objects with the same name always appear in the same order.

  • Related