Reputation: 51
I would like to make a queryset, which will first order by title then by size, but the size should be custom ordered, like the order in the list. For example
order_size_ist = ['S', 'M', 'L', 'XL', 'XXL' ]
queryset = RawMaterial.objects.order_by('title', 'size')
The size should be ordered first S, then M then L and so on. Any ideas ? Thank you in advance :)
Upvotes: 3
Views: 379
Reputation: 476503
You can work with a Case
-When
sequence to map the sizes onto integers and then sort by these integers:
from django.db.models import Case, Value, When
RawMaterial.objects.order_by(
'title',
Case(
*[When(size__iexact=siz, then=Value(i))
for i, siz in enumerate(order_size_ist)],
default=None
).asc()
)
Upvotes: 2