Skip to content

Instantly share code, notes, and snippets.

@RecNes
Last active July 24, 2020 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RecNes/dc8bf54f574f7b70ea0f7ee12828e1d5 to your computer and use it in GitHub Desktop.
Save RecNes/dc8bf54f574f7b70ea0f7ee12828e1d5 to your computer and use it in GitHub Desktop.
Sort object list in python
def sort_query_set_objects(query_set, attr=None):
"""
Convert queryset to a list array and sort by field with order ASC/DESC.
Use when you have to apply ordering to queryset but don't want to do it via database.
:param query_set: queryset
:param attr: query object attribute (field) name with order direction. Usage is same as order_by()
:return: list array w/wo sorted
"""
object_list = list(query_set)
if attr is None:
return object_list
else:
if attr.startswith("-"):
reverse = True
attr_name = attr[1:]
else:
reverse = False
attr_name = attr
from operator import attrgetter
object_list.sort(key=attrgetter(attr_name), reverse=reverse)
return object_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment