按列表中的值对queryset进行排序 [英] Sort queryset by values in list

查看:60
本文介绍了按列表中的值对queryset进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过查询中提供的元素列表对Django查询集进行排序?例如,如果我这样做

Is it possible to sort a django queryset by the list of elements provided in the query? For example, if I do

m.objects.filter(id__in=[3,1,8])

我将查询集的顺序设为id 3的元素,id 1的元素和id 8的元素.

I wan't the order of the queryset to be the element of id 3, the element of id 1 and the element of id 8.

谢谢

推荐答案

由于在Django> = 1.11中存在 Case When 一种类似的方式来保留您的查询集的所有好处:

Since there exists Case and When in Django >= 1.11 you can do it in a more orm-like way keeping all the benefits of your queryset:

from django.db import models

order = ['b', 'a', 'z', 'x', 'c']
whens = []
for sort_index, value in enumerate(order):
    whens.append(models.When(my_field=value, then=sort_index))

qs = MyModel.objects.annotate(_sort_index=models.Case(*whens, output_field=models.IntegerField()))
qs.order_by('_sort_index')

这将生成如下内容:

from django.db import models

order = ['b', 'a', 'z', 'x', 'c']
qs = MyModel.objects.annotate(
    _sort_index=models.Case(
        models.When(my_field='b', then=0),
        models.When(my_field='a', then=1),
        models.When(my_field='z', then=2),
        models.When(my_field='x', then=3),
        models.When(my_field='c', then=4),
        output_field=models.IntegerField()
    )
).order_by('_sort_index')

我建议仅将其与少量列表项一起使用,因为它会炸毁数据库查询.

I would suggest to use this only with a small amount of list-items because it blows up the database-query.

https://docs.djangoproject.com/ko/1.11/ref/models/conditional-expressions/#case

这篇关于按列表中的值对queryset进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆