Thursday 26 May 2016

order_by in django template


put this code into a file in a folder "templatetags" inside some application and use it like this:

in django template

{% load your_file_name %}

{% for item in your_list|order_by:"field1,-field2,other_class__field_name" %}


temp.py inside the template tag folder

from django.template import Library
register = Library()

@register.filter_function
def order_by(queryset, args):
    args = [x.strip() for x in args.split(',')]
    return queryset.order_by(*args)

No comments:

Post a Comment