问题
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 that 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?
回答1:
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))
回答2:
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)
回答3:
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]
回答4:
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'])
来源:https://stackoverflow.com/questions/7361243/django-in-query-lookup-doesnt-maintain-the-order-in-querset