@register.filter
def sort_by(items, attr):
 def key_func(item):
  try:
   return getattr(item, attr)
  except AttributeError:
   try:
    return item[attr]
   except TypeError:
    getattr(item, attr)
 return sorted(items, key=key_func)

@ register . filter def sort_by ( items , attr ) : def key_func ( item ) : try : return getattr ( item , attr ) except AttributeError : try : return item [ attr ] except TypeError : getattr ( item , attr ) return sorted ( items , key = key_func )
general sort filter - sorts by either attribute or key .