djangodjango-querysetstable-sort

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


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?


Solution

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