Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 496
rubayeet Avatar asked Feb 01 '10 11:02

rubayeet


People also ask

Does order of filter matter Django?

If you are just doing two simple filter operations, then you're correct that order doesn't matter, but be careful. There are examples of when the order of your queryset methods do matter: https://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses.

Which operators can be used to access the fields in the object by Django ORM?

You use a period (.) to access the fields in the Django ORM object.


1 Answers

q = Ticket.objects.extra(select={'is_top': "status = 4"}) q = q.extra(order_by = ['-is_top']) 
like image 174
Ofri Raviv Avatar answered Sep 25 '22 12:09

Ofri Raviv