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 all 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
72 changes: 72 additions & 0 deletions docs/pages/order-by-accessors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,75 @@ the ``orderable`` argument::
class SimpleTable(tables.Table):
name = tables.Column()
actions = tables.Column(orderable=False)


.. _table.order_foo:

:meth:`table.order_FOO` methods
--------------------------------

Another solution for alternative ordering is being able to chain functions on to
the original queryset. This method allows more complex functionality giving the
ability to use all of Django's QuerySet API.

Adding a `Table.order_FOO` method (where `FOO` is the name of the column),
gives you the ability to chain to, or modify, the original queryset when that
column is selected to be ordered.

The method takes two arguments: `queryset`, and `is_descending`. The return
must be a tuple of two elements. The first being the queryset and the second
being a boolean; note that modified queryset will only be used if the boolean is
`True`.

For example, let's say instead of ordering alphabetically, ordering by
amount of characters in the first_name is desired.
The implementation would look like this:
::

# tables.py
from django.db.models.functions import Length

class PersonTable(tables.Table):
name = tables.Column()

def order_name(self, queryset, is_descending):
queryset = queryset.annotate(
length=Length('first_name')
).order_by(('-' if is_descending else '') + 'length')
return (queryset, True)



As another example, presume the situation calls for being able to order by a
mathematical expression. In this scenario, the table needs to be able to be
ordered by the sum of both the shirts and the pants. The custom column will
have its value rendered using :ref:`table.render_FOO`.

This can be achieved like this:
::

# models.py
class Person(models.Model):
first_name = models.CharField(max_length=200)
family_name = models.CharField(max_length=200)
shirts = models.IntegerField()
pants = models.IntegerField()


# tables.py
from django.db.models import F

class PersonTable(tables.Table):
clothing = tables.Column()

class Meta:
model = Person

def render_clothing(self, record):
return str(record.shirts + record.pants)

def order_clothing(self, queryset, is_descending):
queryset = queryset.annotate(
amount=F('shirts') + F('pants')
Copy link
Owner

Choose a reason for hiding this comment

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

Just curious: could I use record.amount in render_clothing now?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, but only if you are ordering it by clothing. If the user specifies a different column's order then that attribute won't be there.

).order_by(('-' if is_descending else '') + 'amount')
return (queryset, True)
28 changes: 28 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,33 @@ 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
order_by = 'first_name'

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')
).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