Skip to content

Commit

Permalink
added ability to specify default sort direction
Browse files Browse the repository at this point in the history
  • Loading branch information
drewyeaton committed Apr 12, 2012
1 parent c034f44 commit bd1bf67
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
18 changes: 15 additions & 3 deletions django_sortable/templatetags/sortable.py
Expand Up @@ -23,7 +23,10 @@ def parse_tag_token(token):
try:
title = bits[2]
except IndexError:
title = bits[1].capitalize()
if bits[1].startswith(('+', '-')):
title = bits[1][1:].capitalize()
else:
title = bits[1].capitalize()

return (bits[1].strip(), title.strip())

Expand All @@ -32,7 +35,16 @@ class SortableLinkNode(template.Node):
"""Build sortable link based on query params."""

def __init__(self, field_name, title):
self.field_name = field_name
if field_name.startswith('-'):
self.field_name = field_name[1:]
self.default_direction = 'desc'
elif field_name.startswith('+'):
self.field_name = field_name[1:]
self.default_direction = 'asc'
else:
self.field_name = field_name
self.default_direction = 'asc'

self.title = title


Expand All @@ -56,7 +68,7 @@ def build_link(self, context):
if self.field_name == field_name:
get_params['dir'] = directions[direction]['inverse']
else:
get_params['dir'] = 'asc'
get_params['dir'] = self.default_direction

if self.field_name == field_name:
css_class = directions[direction]['class']
Expand Down
11 changes: 11 additions & 0 deletions readme.md
Expand Up @@ -188,6 +188,17 @@ Notice that we have a tuple for the fields argument, and one of the items in the
Defining ordering fields has the secondary benefit of locking down which fields are sorted on.


####Specifying a Default Sort Direction

The default sort direction for all fields is ascending. This is probably fine for textual data, but for numbers it's nice to default to largest first. To specify a default sort direction of descending, place a `-` before the sort column in the sortable header tag. Here's an example:

{% sortable_header -page_count "Number of Pages" %}

This tag generates a table header (with a default direction of descending) like this:

<th class="sort-none"><a href="/books/?sort=page_count&dir=desc" title="Number of Pages">Number of Pages</a></th>


####Sorting on Multiple Database Columns

If you need more control with exactly how sorting happens, you can specify more than one column to sort by. This works with either Query Sets, lists/tuples of dictionaries or lists/tuples of objects.
Expand Down

0 comments on commit bd1bf67

Please sign in to comment.