Home > Back-end >  Order strings fields in django QuerySet by specific order
Order strings fields in django QuerySet by specific order

Time:10-04

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!

CodePudding user response:

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

  • Related