QuerySet按ID自定义排序

QuerySet按ID自定义排序

本文介绍了Django QuerySet按ID自定义排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出了一个ids / pks列表,我想生成列表中索引排序的对象的 QuerySet



通常我从...开始:

  pk_list = [5,9,2,14] 
queryset = MyModel.objects.filter(pk__in = pk_list)

这当然会返回对象,但是按照模型元排序属性的顺序,并且我希望以 pk_list pk 的顺序获取记录c $ c>。

最终结果必须是一个 QuerySet object不是列表),因为我希望将订单的 QuerySet 传递给Django的 ModelMultipleChoiceField 表单字段。

解决方案

没有内置的方式来做到这一点。



如果你使用MySQL,您可以使用该数据库的 FIELD()函数在您的模型上设置自定义排序顺序,并按此排序。这将工作:

  pk_list = [5,9,2,14] 
ordering ='FIELD `,%s)'%','。join(str(id)for p in pk_list)
queryset = MyModel.objects.filter(pk__in = [pk_list])。extra(
select = 'order':ordering},order_by =('ordering',))


Given a list of ids/pks, I'd like to generate a QuerySet of objects ordered by the index in the list.

Normally I'd begin with:

pk_list = [5, 9, 2, 14]
queryset = MyModel.objects.filter(pk__in=pk_list)

This of course returns the objects, but in the order of the models meta ordering property, and I wish to get the records in the order of the pks in pk_list.

The end result has to be one QuerySet object (not a list), as I wish to pass the ordered QuerySet to Django's ModelMultipleChoiceField form field.

解决方案

There isn't a built-in way to do this.

If you're using MySQL, you can use that database's FIELD() function to set up a custom ordering sequence on your model, and sort by that. This would work:

pk_list = [5, 9, 2, 14]
ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in pk_list)
queryset = MyModel.objects.filter(pk__in=[pk_list]).extra(
               select={'ordering': ordering}, order_by=('ordering',))

这篇关于Django QuerySet按ID自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:01