Skip to content

Instantly share code, notes, and snippets.

@gaozhidf
Forked from chriskief/query.py
Created October 19, 2018 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaozhidf/8e871b2182d18f8470e9e45ffbc7326c to your computer and use it in GitHub Desktop.
Save gaozhidf/8e871b2182d18f8470e9e45ffbc7326c to your computer and use it in GitHub Desktop.
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']
)
@gaozhidf
Copy link
Author

from: https://chriskief.com/2015/01/13/sort-django-query-order-by-using-values-within-in/

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment