Created
November 19, 2012 18:47
-
-
Save dgouldin/4112800 to your computer and use it in GitHub Desktop.
django orm order by list of 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
from django.contrib.auth.models import User | |
user_ids = list(User.objects.values_list('id', flat=True)[:10]) | |
reverse_user_ids = user_ids[::-1] | |
values_str_parts = ['(%s, %s)' % (i, id) for i, id in enumerate(reverse_user_ids)] | |
values_str = 'VALUES %s' % ' '.join(values_str_parts) | |
users = User.objects.raw(""" | |
SELECT u.* | |
FROM auth_user AS u | |
JOIN (%s) AS i (ordering, id) on u.id = i.id | |
ORDER BY i.ordering | |
""" % values_str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment