Python / Django — Combine Querysets and Sort. Sort List of Any Objects.

Assuming it quacks like a duck, you can use operator.attrgetter()

Combine queryset by turning it into a list:
queryset_list = list(queryset1).extend(list(queryset2))

Sort the list by:
queryset_list.sort(key=operator.attrgetter(‘attribute to sort by’))

Update: 4/28/2010

Yeah, I forgot the sort function sorts in place. sort = list.sort would not be good.
Also, for those wondering, you can just import operator. “import operator”

2 Comments

  1. Charlie says:

    very useful, thanks

    1. Yuji says:

      Hey Charlie, thanks for the comment! Glad it helped!

Leave a Comment