从Django的特定的顺序编号的数组得到一个QuerySet [英] Django get a QuerySet from array of id's in specific order

查看:1155
本文介绍了从Django的特定的顺序编号的数组得到一个QuerySet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继承人一个快速为你:

我的ID,我想用返回一个QuerySet(或数组如果需要的话)的列表,但我要维护秩序。

I have a list of id's which I want to use to return a QuerySet(or array if need be), but I want to maintain that order.

感谢

推荐答案

我不认为你可以强制在数据库级别特定的顺序,所以你需要做的是在Python来代替。

I don't think you can enforce that particular order on the database level, so you need to do it in python instead.

id_list = [1, 5, 7]
objects = Foo.objects.filter(id__in=id_list)

objects = dict([(obj.id, obj) for obj in objects])
sorted_objects = [objects[id] for id in id_list]

这建立了与他们的id作为重点对象的字典,所以建立排序列表时,他们可以轻松地检索。

This builds up a dictionary of the objects with their id as key, so they can be retrieved easily when building up the sorted list.

这篇关于从Django的特定的顺序编号的数组得到一个QuerySet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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