Skip to content

Commit

Permalink
add fix for sort by relation (#304)
Browse files Browse the repository at this point in the history
  • Loading branch information
aleontiev authored Jun 23, 2020
1 parent 3634762 commit 4a9200e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
7 changes: 5 additions & 2 deletions dynamic_rest/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 9 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={
Expand Down

0 comments on commit 4a9200e

Please sign in to comment.