errMSG
errMSG

Reputation: 155

Is there a way to use order_by in Django to specify the order in which the results are returned?

So far I have seen only ascending and descending uses for order_by. I want to order_by(Risk) but have the results returned in High, Med, Low order (These are my options in the field), not based on alphabet sorting, the way order_by is done by default.

To explain it a different way...I have a Field in my model called "Risk". Risk only has 3 values across all the records, High,Med,Low. When I run queries on the database I want it to sort the results of the query based on the the field Risk in the order of High,Med,Low, not the random order it is returning the records now.

current code looks like this:

    items = ScanData.objects.filter(Q(Owner__icontains="HooliCorp")).order_by(Risk)

Upvotes: 3

Views: 369

Answers (1)

GwynBleidD
GwynBleidD

Reputation: 20569

One solution is to annotate your query with some conditional statement that will output a number depending on the field value:

items = ScanData.objects.filter(
    Q(Owner__icontains="HooliCorp")
).annotate(
    risk_order=models.Case(
        models.When(Risk='Low', then=1),
        models.When(Risk='Med', then=2),
        models.When(Risk='High', then=3),
        output_field=models.IntegerField(),
    ),
).order_by('risk_order')

This will create an annotation on the results list with a number from 1 to 3, depending on the risk value and then it will order the query by this annotation.

Upvotes: 2

Related Questions