Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Column ordering queryset passthrough #330

Merged
merged 4 commits into from
May 23, 2016
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions django_tables2/columns/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,18 @@ def render(self, value):
"""
return value

def order(self, queryset, is_descending):
"""
Returns the queryset of the table.

This method can be overridden by :ref:`table.order_FOO` methods on the
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this reference point to anything?

Copy link
Contributor Author

@michaelmob michaelmob May 19, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

table.order_FOO is a placeholder name, so no, it doesn't point to a real function. Would you like me to rephrase it?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say to either add some documentation or do not reference it.

Of course, more documentation is better.

table or by subclassing `.Column`; but only overrides if second element
in return tuple is True.

:returns: Tuple (queryset, boolean)
"""
return (queryset, False)

@classmethod
def from_field(cls, field):
"""
Expand Down Expand Up @@ -527,6 +539,7 @@ def __init__(self, table):
for name, column in six.iteritems(table.base_columns):
self.columns[name] = bc = BoundColumn(table, column, name)
bc.render = getattr(table, 'render_' + name, column.render)
bc.order = getattr(table, 'order_' + name, column.order)

def iternames(self):
return (name for name, column in self.iteritems())
Expand Down
7 changes: 7 additions & 0 deletions django_tables2/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ def order_by(self, aliases):
regard to data ordering.
:type aliases: `~.utils.OrderByTuple`
"""
bound_column = None
accessors = []
for alias in aliases:
bound_column = self.table.columns[OrderBy(alias).bare]
Expand All @@ -102,6 +103,12 @@ def order_by(self, aliases):
else:
accessors += bound_column.order_by
if hasattr(self, 'queryset'):
# Custom ordering
if bound_column:
self.queryset, modified = bound_column.order(self.queryset, alias[0] == '-')
if modified:
return
# Traditional ordering
translate = lambda accessor: accessor.replace(Accessor.SEPARATOR, QUERYSET_ACCESSOR_SEPARATOR)
if accessors:
self.queryset = self.queryset.order_by(*(translate(a) for a in accessors))
Expand Down
27 changes: 27 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# coding: utf-8
import pytest
from django.utils import six
from django.db.models.functions import Length

import django_tables2 as tables

Expand Down Expand Up @@ -297,6 +298,32 @@ class Meta:
assert table.rows[0].get_cell('first_name') == 'Stevie'


def test_queryset_table_data_supports_custom_ordering():
class Table(tables.Table):
class Meta:
model = Person

def order_first_name(self, queryset, is_descending):
# annotate to order by length of first_name + last_name
queryset = queryset.annotate(
length=Length("first_name") + Length("last_name")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use single quotes if possible.

).order_by(('-' if is_descending else '') + 'length')
return (queryset, True)

for name in ('Bradley Ayers', 'Stevie Armstrong', 'VeryLongFirstName VeryLongLastName'):
first_name, last_name = name.split()
Person.objects.create(first_name=first_name, last_name=last_name)

table = Table(Person.objects.all())

# Shortest full names first
assert table.rows[0].get_cell('first_name') == 'Bradley'

# Longest full names first
table.order_by = '-first_name'
assert table.rows[0].get_cell('first_name') == 'VeryLongFirstName'


def test_doesnotexist_from_accessor_should_use_default():
class Table(tables.Table):
class Meta:
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ usedevelop = true
pip_pre = true
setenv = PYTHONPATH={toxinidir}
commands =
py.test --cov=django_tables2 --cov-report term-missing
py.test tests --cov=django_tables2 --cov-report term-missing
flake8

deps =
Expand Down