Order strings fields in django QuerySet by specific order

Question:

I have a string field status that accepts 3 values

  1. "ON_ITS_WAY"
  2. "DELIVERED"
  3. "PACKAGING"

I want to be able to sort queryset objects by the status field by custom deciding the order :

"DELIVERED" > "ON_ITS_WAY" > "PACKAGING"

so meaning every record with the status "DELIVERED" will appear first and so on.

haven’t found a way to do it with Django :(, can anyone help?
thanks!

Asked By: Itai Bar

||

Answers:

let’s Imagine your model is called Order, then your queryset will look like this.

preference = Case(
        When(status="DELIVERED", then=Value(0)),
        When(status="ON_ITS_WAY", then=Value(1)),
        When(status="PACKAGING", then=Value(2))
)
query_set = Order.objects.alias(preference=preference).order_by('preference')

Check these methods from Official Django Docs:

When

Case

alias

Answered By: Mahmoud Nasser
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.