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) |
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))}, | |
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()`.