I wrote a messy function and I am wondering if you see any way I could clean it up. Essentially it takes in a list e_1=2&e_2=23&e_3=1
and makes a queryset out of it, maintaining the ordering.
from operator import itemgetter
def ids_to_students(items, prefix=0):
if prefix == 0:
# Make ordered QuerySets of Students based on there ids
etuples = sorted([(k,v) for k,v in items if k[:2] == 'e_'], key=itemgetter(0))
ituples = sorted([(k,v) for k,v in items if k[:2] == 'i_'], key=itemgetter(0))
tuples = etuples+ituples
else:
tuples = sorted([(k,v) for k,v in items if k[:2] == '%s_'%prefix], key=itemgetter(0))
pk_list = [v for (k,v) in tuples]
clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(pk_list)])
ordering = 'CASE %s END' % clauses
students = Student.objects.filter(pk__in=pk_list).extra(
select={'ordering': ordering}, order_by=('ordering',))
return students
It's called like this:
students = ids_to_students(request.GET.items())
e_students = ids_to_students(request.GET.items(), 'e')