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:

SELECT id, name
FROM table
WHERE name IN (9, 8, 1, 2, 7, 3)
ORDER BY FIELD(id, 9, 8, 1, 2, 7, 3)

view raw


hosted with ❤ by GitHub

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.

ids = [9, 8, 1, 2, 7, 3]
results = Model.objects.filter(id__in=ids).extra(
select={'manual': 'FIELD(id,%s)' % ','.join(map(str, ids))},

view raw

hosted with ❤ by GitHub

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: Logo

You are commenting using your 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 )

Connecting to %s