Django: __in query lookup doesn't maintain the order in queryset

后端 未结 4 1509
Happy的楠姐
Happy的楠姐 2020-12-23 21:11

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, publi         


        
4条回答
  •  不思量自难忘°
    2020-12-23 21:43

    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))
    

提交回复
热议问题