如何使用Django从queryset中排序一个列表



我想对从queryset转换的列表进行排序。我试过使用sorted,但我得到一个错误

这是我的代码:

views.py

@api_view(['GET'])
def practiceAnswer_filter(request):
# GET list of filtered practiceAnswer
if request.method == 'GET':
practiceAnswers = PracticeAnswer.objects.all()

practice_id = request.GET.get('practice_id', None)
if practice_id is not None:
# filter practiceAnswer based on practice_id
practiceAnswer_filtered = practiceAnswers.filter(practice_id__practice_id__icontains=practice_id)
# convert queryset to list
practiceAnswer_list = list(practiceAnswer_filtered)
# shuffle to get random practiceAnswer
shuffle(practiceAnswer_list)
# splice list to limit practiceAnswer
practiceAnswer_shuffled = practiceAnswer_list[:3]

practiceAnswer_sort = practiceAnswer_shuffled
dict(sorted(practiceAnswer_sort.items(), key=lambda item: item[1]))
print(practiceAnswer_sort)

practiceAnswers_serializer = PracticeAnswerSerializer(practiceAnswer_sort, many=True)
return JsonResponse(practiceAnswers_serializer.data, safe=False)

这是来自queryset的原始数据:

<QuerySet [<PracticeAnswer: 1>, <PracticeAnswer: 2>, <PracticeAnswer: 3>]>

这是从查询集到列表的转换数据:

[<PracticeAnswer: 1>, <PracticeAnswer: 2>, <PracticeAnswer: 3>]

实际上,对于原始数据和转换后的数据,我已经得到了排序的数据,但从原始数据中,我仍然通过基于practice_id过滤它并随机化数据来处理它,以便在限制/拼接之后获得随机数据,仅显示3个数据。没有sorted,出现的3个数据不是顺序的,我希望数据按值1、2、3排序

如果我运行上面的代码,我得到一个错误:
AttributeError at /api/practice-answer-filter
'list' object has no attribute 'items'

如何修复?我不知道该怎么办。请帮帮我。谢谢你。

我想你可以这样使用.sort:

def sort_list(e):
return e.pk

practiceAnswer_shuffled.sort(key=sort_list)

关于sort的更多信息

相关内容

  • 没有找到相关文章

最新更新