问题描述
给出了一个ids / pks列表,我想生成列表中索引排序的对象的 QuerySet
。
通常我从...开始:
pk_list = [5,9,2,14]
queryset = MyModel.objects.filter(pk__in = pk_list)
这当然会返回对象,但是按照模型元排序属性的顺序,并且我希望以 最终结果必须是一个 没有内置的方式来做到这一点。 如果你使用MySQL,您可以使用该数据库的 Given a list of ids/pks, I'd like to generate a Normally I'd begin with: 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 The end result has to be one There isn't a built-in way to do this. If you're using MySQL, you can use that database's 这篇关于Django QuerySet按ID自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! pk_list $中的
pk
的顺序获取记录c $ c>。
QuerySet
object不是列表),因为我希望将订单的 QuerySet
传递给Django的 ModelMultipleChoiceField
表单字段。
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',))
QuerySet
of objects ordered by the index in the list.pk_list = [5, 9, 2, 14]
queryset = MyModel.objects.filter(pk__in=pk_list)
pk
s in pk_list
.QuerySet
object (not a list), as I wish to pass the ordered QuerySet
to Django's ModelMultipleChoiceField
form field.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',))