Stanislav Rybonka
Stanislav Rybonka

Reputation: 23

How to use multiple order_by in single Django query with conditions based on field values

How can I make order_by fields in a single query dependent on field values?

e.g.,

Upvotes: 2

Views: 1847

Answers (1)

Dima  Kudosh
Dima Kudosh

Reputation: 7386

You can use conditions in your order_by like this:

from django.db.models import Case, When

Model.objects.order_by(
    Case(When(status='10', then='some_field')).asc(),
    Case(When(status='20', then='some_field')).desc())

Upvotes: 5

Related Questions