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

2👍

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.

Leave a comment