Skip to content

Instantly share code, notes, and snippets.

@dgouldin
Created November 19, 2012 18:47
Show Gist options
  • Save dgouldin/4112800 to your computer and use it in GitHub Desktop.
Save dgouldin/4112800 to your computer and use it in GitHub Desktop.
django orm order by list of ids
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