Skip to content

Commit

Permalink
allow columns to be reordered by given keys
Browse files Browse the repository at this point in the history
  • Loading branch information
guruofgentoo committed Sep 9, 2021
1 parent 7549824 commit affcb54
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions webgrid/__init__.py
Expand Up @@ -986,6 +986,20 @@ def post_init(self):
"""
pass

def set_column_order(self, column_keys):
"""Most renderers output columns in the order they appear in the grid's ``columns``
list. When bringing mixins together or subclassing a grid, however, the order is
often not what is intended.
This method allows a manual override of column order, based on keys."""
key_check = set(column_keys) - set(self.key_column_map.keys())
if key_check:
raise Exception(f'Keys not recognized on grid: {key_check}')

self.columns = [
self.key_column_map[key] for key in column_keys
]

def before_query_hook(self):
"""Hook to give subclasses a chance to change things before executing the query.
"""
Expand Down
13 changes: 13 additions & 0 deletions webgrid/tests/test_unit.py
Expand Up @@ -184,6 +184,19 @@ def query_prep(self, query, has_sort, has_filters):
g = CTG()
assert_in_query(g, 'ORDER BY persons.last_name')

def test_column_reorder(self):
class CTG(Grid):
Column('First Name', Person.firstname, TextFilter)
Column('Last Name', Person.lastname, TextFilter)

grid = CTG()
grid.set_column_order(('lastname', 'firstname'))
assert grid.columns[-1].label == 'First Name'
assert grid.columns[0].label == 'Last Name'

with pytest.raises(Exception, match="Keys not recognized on grid: {'foo'}"):
grid.set_column_order(('foo', ))

def test_filter_class(self):
class CTG(Grid):
Column('First Name', Person.firstname, TextFilter)
Expand Down

0 comments on commit affcb54

Please sign in to comment.