Sort Django Query (Order By) Using Values Within IN()

In MySQL, you can use the FIELD() function to easily sort a result set by a list of ordered ids:

To accomplish this in Django, you can make use of the extra() QuerySet method to create an additional field in the SELECT statement which can then be using for sorting in the FIELD method.

One thought on “Sort Django Query (Order By) Using Values Within IN()”

  1. You could also use the `.in_bulk()` method. It won’t sort the results (it returns a dictionary), but you can then easily construct a sorted list from the results. This only works when selecting on the primary key, but the upside is that it doesn’t require a database-specific function like MySQL’s `FIELD()`.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s