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

Fix backwards-compatibility with legacy separators in order_by clauses #715

Merged
merged 2 commits into from
Nov 20, 2019
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
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
18 changes: 13 additions & 5 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ 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 'a.b'"
with self.assertWarnsRegex(DeprecationWarning, 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 All @@ -89,11 +100,8 @@ def test_calling_methods(self):
self.assertEqual(Accessor("2__upper").resolve("Brad"), "A")

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):
message = "Use '__' to separate path components, not '.' in accessor '2.upper'"
with self.assertWarnsRegex(DeprecationWarning, message):
Accessor("2.upper")

def test_honors_alters_data(self):
Expand Down