Manager.in_bulk 只是返回一个字典,所以没有办法强制它有一个特定的顺序。
如果您想要的只是与 ID 列表匹配的对象列表,按 ID 排序,那么请执行以下操作:
id_list = [1, 2, 3, 10, 11, 12]
results = MyModel.objects.filter(id__in=id_list).order_by('id')
它的效率可能不如.in_bulk(),但比一次查询一个要好得多。
但是,如果您想要一个非常具体的顺序 - 说“按照 Redis 返回它们的顺序” - 没有办法让数据库本身这样做。就其性质而言,关系数据库返回一组无序的行,除非您应用排序,但该排序必须基于数据库的字段。
此时,您最好的选择是使用 .in_bulk() 获取对象字典,以 ID 为键,然后查找该字典以按照您需要的顺序构建一个列表:
已编辑:如果您要对结果进行重新排序,则应注意数据库未返回您请求的某些 ID 的可能性。您可以使用 results.get(id, None) 安全地索引到字典中,并使用 filter() 从列表中删除空项目。
id_list = [10, 11, 12, 1, 2, 3]
# Get all of the items from the database
results = MyModel.objects.in_bulk(id_list)
# re-order the results into the order specified by id_list
ordered_results = [results.get(id,None) for id in id_list]
# remove None items from the ordered results
filtered_results = filter(None, ordered_results)