I have a queryset I want to sort based on a custom ordering of the label
field.
This is the function I have to sort labels appropriately:
def sort_question_labels(labels):
def num_split_test(string):
key = "".join([s for s in itertools.takewhile(lambda x: x.isdigit(), list(string))])
try:
return int(key)
except:
return key
def str_split_test(string):
num_part_len = len(str(num_split_test(string)))
return string[num_part_len:]
labels2 = sorted(labels, key=str_split_test)
return sorted(labels2, key=num_split_test)
So sort_question_labels(['a', '1', '11', '1a', '6f', '6', '6a'])
returns ['1', '1a', '6', '6a', '6f', '11', 'a']
.
In the admin, I am trying to sort the queryset for my question
model according to the label
field. I want to do something along the lines of:
def get_queryset(self, request):
qs = super(MultQAdmin, self).get_queryset(request)
return qs.distinct() \
.annotate(sort_num = sort_question_labels('label')) \
.order_by('sort_num')
though obviously this is nowhere near right. I can rewrite the sort function as necessary to accommodate whatever format is needed.