Skip to content

Commit

Permalink
Fix backwards-compatibility with legacy separators in order_by clauses
Browse files Browse the repository at this point in the history
  • Loading branch information
federicobond committed Nov 19, 2019
1 parent 1eda716 commit 6dc8149
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
14 changes: 13 additions & 1 deletion django_tables2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ class OrderBy(str):

QUERYSET_SEPARATOR = "__"

def __new__(cls, value):
instance = super().__new__(cls, value)
if Accessor.LEGACY_SEPARATOR in value:
message = (
"Use '__' to separate path components, not '.' in accessor '{}'"
" (fallback will be removed in django_tables2 version 3)."
).format(value)

warnings.warn(message, DeprecationWarning, stacklevel=3)

return instance

@property
def bare(self):
"""
Expand Down Expand Up @@ -118,7 +130,7 @@ def for_queryset(self):
Returns the current instance usable in Django QuerySet's order_by
arguments.
"""
return self.replace(Accessor.SEPARATOR, OrderBy.QUERYSET_SEPARATOR)
return self.replace(Accessor.LEGACY_SEPARATOR, OrderBy.QUERYSET_SEPARATOR)


class OrderByTuple(tuple):
Expand Down
14 changes: 14 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ def test_orderby_descending(self):
self.assertTrue(b.is_descending)
self.assertFalse(b.is_ascending)

def test_error_on_legacy_separator(self):
message = (
"Use '__' to separate path components, not '.' in accessor '2.upper'"
" (fallback will be removed in django_tables2 version 3)."
)
with self.assertWarns(DeprecationWarning, msg=message):
OrderBy("a.b")

def test_for_queryset(self):
ab = OrderBy("a.b")
self.assertEqual(ab.for_queryset(), "a__b")
ab = OrderBy("a__b")
self.assertEqual(ab.for_queryset(), "a__b")


class AccessorTest(TestCase):
def test_bare(self):
Expand Down

0 comments on commit 6dc8149

Please sign in to comment.