2

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.

Julia Ebert
  • 1,583
  • 1
  • 21
  • 39
  • possible duplicate of [django - ordering queryset by a calculated field](http://stackoverflow.com/questions/1652577/django-ordering-queryset-by-a-calculated-field) – Peter DeGlopper Sep 17 '14 at 18:30
  • I'm not looking to order by a field. I had looked at `.extra(order_by...)`, but that only works for database fields, not methods. – Julia Ebert Sep 17 '14 at 19:13
  • 1
    Ordering in the queryset happens in the database, so you can't order by an arbitrary Python method. If you can express your ordering criteria in a way that can be calculated in the database, the linked answer or one of the others that link to it should show how to use `extra` to do that. If not, you're probably stuck sorting in memory in Python. – Peter DeGlopper Sep 17 '14 at 19:15

0 Answers0