Django:__in 查询查找不维护查询集中的顺序
我有特定顺序的 ID,
>>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
>>> albums = Album.objects.filter( id__in=album_ids, published= True )
>>> [album.id for album in albums]
[25, 24, 27, 28, 26, 11, 15, 19]
我需要查询集中的相册与 album_ids
中的 id 的顺序相同。有人请告诉我如何维持订单吗?或获取专辑如 album_ids 中那样?
I have ID's in a specific order
>>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
>>> albums = Album.objects.filter( id__in=album_ids, published= True )
>>> [album.id for album in albums]
[25, 24, 27, 28, 26, 11, 15, 19]
I need albums in queryset in the same order as id's in album_ids
. Anyone please tell me how can i maintain the order? or obtain the albums as in album_ids?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设 ID 列表不太大,您可以将 QS 转换为列表并在 Python 中对其进行排序:
Assuming the list of IDs isn't too large, you could convert the QS to a list and sort it in Python:
你不能在 django 中通过 ORM 来做到这一点。
但自己实现起来非常简单:
You can't do it in django via ORM.
But it's quite simple to implement by youself:
对于 Django 版本 >= 1.8,请使用以下代码:
这是数据库级别的 PostgreSQL 查询表示:
For Django versions >= 1.8, use below code:
Here is the PostgreSQL query representation at database level:
您可以使用 额外 QuerySet 修饰符
You can do it in Django via ORM using the extra QuerySet modifier
使用 @Soitje 的解决方案: https://stackoverflow.com/a/37648265/1031191
请注意,您需要确保 album_ids 是唯一的。
备注:
1.) 该解决方案应该可以安全地与任何其他字段一起使用,而不会面临 SQL 注入攻击的风险。
2.)
案例
(Django doc) 生成一个类似于 https://stackoverflow.com/a/33753187/1031191Using @Soitje 's solution: https://stackoverflow.com/a/37648265/1031191
Note that you need to make sure that album_ids are unique.
Remarks:
1.) This solution should safely work with any other fields, without risking an sql injection attack.
2.)
Case
(Django doc) generates an sql query like https://stackoverflow.com/a/33753187/1031191如果您使用 MySQL 并希望通过使用字符串列来保留顺序。
If you use MySQL and want to preserve the order by using a string column.