Skip to content

Commit

Permalink
Added (failing) unit test for #413
Browse files Browse the repository at this point in the history
  • Loading branch information
jieter committed Feb 13, 2017
1 parent af3b2bd commit 8a240b0
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
import pytest
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.utils import six
from django_tables2.tables import DeclarativeColumnsMetaclass
from django_tables2.tables import DeclarativeColumnsMetaclass, RequestConfig

from .app.models import Person
from .utils import build_request

request = build_request('/')
Expand Down Expand Up @@ -300,7 +301,7 @@ def test_ordering_different_types():
]

table = OrderedTable(data)
assert "—" == table.rows[0].get_cell('alpha')
assert '—' == table.rows[0].get_cell('alpha')

table = OrderedTable(data, order_by='i')
if six.PY3:
Expand Down Expand Up @@ -784,6 +785,47 @@ class Table(tables.Table):
assert 'canOrder' in table.columns[1].attrs['th']['class']


@pytest.mark.django_db
def test_ordering_by_custom_field():
'''
When defining a custom field in a table, as name=tables.Column() with
methods to render and order render_name and order_name, sorting by this
column causes an error if the custom field is not in last position.
(issue #413)
'''

Person.objects.create(first_name='Alice', last_name='Beta')
Person.objects.create(first_name='Bob', last_name='Alpha')

from django.db.models import F, Value
from django.db.models.functions import Concat


class PersonTable(tables.Table):
first_name = tables.Column()
last_name = tables.Column()
full_name = tables.Column()

def render_full_name(self, record):
return record.last_name + ' ' + record.first_name

def order_full_name(self, queryset, is_descending):
queryset = queryset.annotate(
full_name=Concat(F('last_name'), Value(' '), F('first_name'))
).order_by(('-' if is_descending else '') + 'full_name')
return queryset, True

class Meta:
model = Person
fields = ('first_name', 'last_name', 'full_name')

table = PersonTable(Person.objects.all())
request = build_request('/?sort=full_name&sort=first_name')
RequestConfig(request).configure(table)

assert table.rows[0].record.first_name == 'Bob'


def test_row_attrs():
class Table(tables.Table):
alpha = tables.Column()
Expand Down

0 comments on commit 8a240b0

Please sign in to comment.