From 4a9200e3c9540d54ee4b81e5be643d234b059c90 Mon Sep 17 00:00:00 2001 From: Anthony Leontiev Date: Tue, 23 Jun 2020 15:48:32 -0700 Subject: [PATCH] add fix for sort by relation (#304) --- dynamic_rest/filters.py | 7 +++++-- tests/test_api.py | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/dynamic_rest/filters.py b/dynamic_rest/filters.py index 74eea336..15410e92 100644 --- a/dynamic_rest/filters.py +++ b/dynamic_rest/filters.py @@ -667,8 +667,11 @@ def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: - return queryset.order_by(*ordering) - + queryset = queryset.order_by(*ordering) + if any(['__' in o for o in ordering]): + # add distinct() to remove duplicates + # in case of order-by-related + queryset = queryset.distinct() return queryset def get_ordering(self, request, queryset, view): diff --git a/tests/test_api.py b/tests/test_api.py index 6f2f1358..3e1798e1 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -925,6 +925,15 @@ def test_sort_relation_field_reverse(self): [row['location'] for row in data['users']] ) + def test_sort_relation_field_many(self): + url = '/locations/?sort[]=friendly_cats.name' + response = self.client.get(url) + self.assertEquals(200, response.status_code) + data = json.loads(response.content.decode('utf-8')) + ids = [row['id'] for row in data['locations']] + # no duplicates + self.assertEquals(len(ids), len(set(ids))) + @override_settings( DYNAMIC_REST={