I am trying to create a Django queryset that returns records in a specific order that matches a list of IDs.

我正在尝试创建一个Django查询集,该查询集以特定顺序返回与ID列表匹配的记录。

My list of IDs is:

我的ID列表是:

[34,12,4,89,3,67,11]

If I run the following query:

如果我运行以下查询:

queryset = Item.objects.filter(pk__in=[34,12,4,89,3,67,11])

The query returns records in the ID order:

查询以ID顺序返回记录:

3,4,11,12,34,67,89

Is there any way to make the query return the records in the same order as the list?

有没有办法让查询以与列表相同的顺序返回记录?

If not is there a way to re-order the query result into the required order?

如果没有,是否有办法将查询结果重新排序为所需的顺序?

1 个解决方案

#1


1

Note: Adding this as an answer because OP asked about the approach in the comments of the original question. Showing the snippets in comments didn't allow fenced code blocks.

注意:添加此作为答案,因为OP询问了原始问题的评论中的方法。在注释中显示片段不允许使用受防护的代码块。

In the comments on the original question, I mentioned an alternative solution storing your order numbers in a model field, so that ordered queries would be simpler.

在对原始问题的评论中,我提到了一种替代解决方案,将您的订单号存储在模型字段中,以便有序查询更简单。

One use case for this is if you have a queue of objects where each item is a movie and the user is deciding which order to watch them. You might want to let a Django admin or a user re-order the items (hence making it a field). For the sake of a simple example let's assume there is only one user so we'll build the ordering into the model, as opposed to making a custom table to join through Item and User models.

一个用例就是如果你有一个对象队列,其中每个项目都是一个电影,用户正在决定观看它们的顺序。您可能想让Django管理员或用户重新订购项目(因此将其作为字段)。为了一个简单的例子,我们假设只有一个用户,因此我们将在模型中构建排序,而不是通过Item和User模型建立自定义表。

The model:

class Item(models.Model):
    # ...
    my_order = models.PositiveIntegerField(unique=True)

Set the attribute either at creation or later:

在创建时或以后设置属性:

Item.objects.create(id=34, my_order=1)
Item.objects.create(id=12, my_order=2)
Item.objects.create(id=4, my_order=3)
# ...

Of course, you could create them and set my_order in any order you wished, and the result will still be the same.

当然,您可以按照您希望的任何顺序创建它们并设置my_order,结果仍然是相同的。

Retrieve the objects in desired order:

按所需顺序检索对象:

queryset = Item.objects.order_by('my_order')

更多相关文章

  1. Django的模型。在多个模型类和管理中关联元组
  2. python之全栈开发——————IO模型
  3. 数据挖掘(三)分类模型的描述与性能评估,以决策树为例
  4. 机器学习教程之2-k近邻模型的sklearn实现
  5. Django模型选择:使用元组的第一个元素
  6. 【懒懒的Tensorflow学习笔记三之搭建简单的神经网络模型】
  7. Python多个装饰器的顺序
  8. Django代理模型返回父模型
  9. Tensorflow:恢复图形和模型,然后在单个图像上运行评估

随机推荐

  1. 你的Android,我的Android
  2. android logo、android开机动画改变详解
  3. android 权限注解库
  4. MaterialRangeSlider双向拖动seekbar
  5. Android日常整理(一)---android返回键、Fra
  6. android中的handler的作用
  7. 键盘弹出以后Activity的布局方式
  8. Android 小项目之--SQLite 使用法门 (附源
  9. Android(安卓)wifi-framework WifiMonito
  10. 在Linux下安装Android(安卓)SDK