Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
Ahsan Avatar asked Sep 09 '11 11:09

Ahsan


People also ask

Why are QuerySets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

What is difference between Select_related and Prefetch_related?

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.


1 Answers

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)) 
like image 59
Daniel Roseman Avatar answered Sep 21 '22 00:09

Daniel Roseman