django: __in query lookup doesn't maintain the order in querset

岁酱吖の 提交于 2019-11-29 23:02:57

Assuming the list of IDs isn't too large, you could convert the QS to a list and sort it in Python:

album_list = list(albums)
album_list.sort(key=lambda album: album_ids.index(album.id))

Since Djnago 1.8 you can do in this way

from django.db.models import Case, When

pk_list = [10, 2, 1]
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved)

You can't do it in django via ORM. But it's quite simple to implement by youself:

album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
albums = Album.objects.filter(published=True).in_bulk(album_ids) # this gives us a dict by ID
sorted_albums = [albums[id] for id in albums_ids if id in albums]

You can do it in Django via ORM using the extra QuerySet modifier

>>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
>>> albums = Album.objects.filter( id__in=album_ids, published= True
             ).extra(select={'manual': 'FIELD(id,%s)' % ','.join(map(str, album_ids))},
                     order_by=['manual'])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!