模板对象的有序列表

时间:2014-03-10 21:02:27

标签: python django orm

尝试订购我的查询集。我知道有order_by()但是排序是由POST数据定义的,而不是DB中的任何内容。

sort----lookup-----display objects (darn, orderless)
1. Joe     \     
2. Fred     =>    {Fred, Joe, Marty} 
3. Marty   /

这是我到目前为止的观察代码......

from operator import itemgetter
#...

# Sorted Tuples! Now what?? (this is not used)
i1 = sorted([(k,v) for k,v in request.POST.items() if k[:2] == 'i_'], key=itemgetter(1))
e1 = sorted([(k,v) for k,v in request.POST.items() if k[:2] == 'e_'], key=itemgetter(1))

# Unsorted lists to use in ORM :/
i = [int(v) for k,v in request.POST.items() if k[:2] == 'i_']
e = [int(v) for k,v in request.POST.items() if k[:2] == 'e_']

# It's an orderless QuerySet...
i_students = Student.objects.filter(pk__in=i)
e_students = Student.objects.filter(pk__in=e)

如果您有任何想法,请告诉我:)我想在模板中执行此操作...

<ol>
{% for s in i_students %}
     <li>{{ s }}</li>
{% endfor %}
</ol>

并显示:

1. Joe
2. Fred
3. Marty

1 个答案:

答案 0 :(得分:0)

这回答了我的问题:http://blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html

我从帖子中得到这样的东西:

i_0 -> 3
i_1 -> 26
i_2 -> 12

我会像这样返回已排序的对象:

i_tuples   = sorted([(k,v) for k,v in request.POST.items() if k[:2] == 'i_'], key=itemgetter(0))
i_pk_list  = [v for (k,v) in i_tuples]
clauses    = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(i_pk_list)])
ordering   = 'CASE %s END' % clauses
i_students = Student.objects.filter(pk__in=i_pk_list).extra(
           select={'ordering': ordering}, order_by=('ordering',))

它非常混乱,所以如果有人有更好的排序QuerySets的解决方案,请告诉我。