In MySQL, you can use the FIELD() function to easily sort a result set by a list of ordered ids:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT id, name | |
FROM table | |
WHERE name IN (9, 8, 1, 2, 7, 3) | |
ORDER BY FIELD(id, 9, 8, 1, 2, 7, 3) |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ids = [9, 8, 1, 2, 7, 3] | |
results = Model.objects.filter(id__in=ids).extra( | |
select={'manual': 'FIELD(id,%s)' % ','.join(map(str, ids))}, | |
order_by=['manual'] | |
) |
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()`.