Reputation: 15602
I am trying to order a Django QuerySet by whether a model field value is in a list.
I know that you can filter on this property, like this:
my_qs = MyModel.objects.filter(id__in=[1,3,5,11])
will give me only the MyModel objects with ids 1, 3, 5, and 11.
I'd like to order on this property. Using the above example, I'd like have the MyModel objects with ids in the list first, but still have all the other MyModel objects too, just after them.
Thanks for your help!
Upvotes: 1
Views: 394
Reputation: 99640
my_qs = MyModel.objects.filter(id__in=[1,3,5,11])
not_my_qs = MyModel.objects.exclude(id__in=[1,3,5,11])
from itertools import chain
result_list = list(chain(my_qs, not_my_qs))
Upvotes: 2