Can Django ORM do an ORDER BY on a specific value of a column?

Viewed 7514

I have a table 'tickets' with the following columns

  • id - primary key - auto increment
  • title - varchar(256)
  • status - smallint(6) - Can have any value between 1 and 5, handled by Django

When I'll do a SELECT * I want the rows with status = 4 at the top, the other records will follow them. It can be achieved by the following query:

select * from tickets order by status=4 DESC

Can this query be executed through Django ORM? What parameters should be passed to the QuerySet.order_by() method?

3 Answers
q = Ticket.objects.extra(select={'is_top': "status = 4"})
q = q.extra(order_by = ['-is_top'])

For those in need just like me that stumbled on this now and are using newer versions of django

Ticket.objects.annotate(
            relevancy=Case(When(status=4, then=1), When(status=3, then=2), When(status=2, then=3), output_field=IntegerField())
        ).order_by('-relevancy')

Using Count() will return 1 or 0 depending if your case was found or not. Not ideal if ordering by a couple of status

Related