简体   繁体   English

在Django中对修改后的Queryset进行排序

[英]Sorting a modified Queryset in Django

I'm pull all records from DB and then creating a modified set which is then passed onto the render - this works fine and the added scoring values all all nicely used. 我从DB中提取所有记录,然后创建一个修改后的集合,然后将其传递给渲染 - 这样可以正常工作并且所添加的评分值都可以很好地使用。 Now I would like to sort this modified set but obviously I cannot use the orderby statement as the score values are not columns in the table. 现在我想对这个修改过的集进行排序,但显然我不能使用orderby语句,因为得分值不是表中的列。 However, the .sort function doesn't seem to exist, when I try in the shell. 但是,当我尝试shell时, .sort函数似乎不存在。 Now I could manually create a list, but is there a simpler way and more pythonic way to do this? 现在我可以手动创建一个列表,但有更简单的方法和更pythonic方式来做到这一点?

mylist = AboutMe.objects.all()
for record in mylist:

        record.Score = GenerateScoreFunction(weight_factors, myid, record.id)       
return render(request, 'static/list.html', {'list': mylist, 'loggedin': loggedin})

The type of mylist is a Queryset mylist的类型是Queryset

You can use the sorted() function to return a sorted list based on a given key: 您可以使用sorted()函数返回基于给定键的排序列表:

return render(request, 'static/list.html', {'list': sorted(mylist, key=lambda r: r.Score), 
                                           'loggedin': loggedin})

The most Django way is to see if you can replace the GenerateScoreFunction with annotate and aggregate functions: 最Django的方法是看看你是否可以用注释和聚合函数替换GenerateScoreFunction:

https://docs.djangoproject.com/en/1.6/ref/models/querysets/#annotate https://docs.djangoproject.com/en/1.6/ref/models/querysets/#id5 https://docs.djangoproject.com/en/1.6/ref/models/querysets/#annotate https://docs.djangoproject.com/en/1.6/ref/models/querysets/#id5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM