Skip to content

Commit

Permalink
Fixed fast distinct ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
matllubos committed Mar 22, 2021
1 parent 9266e7a commit 495faaa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
5 changes: 4 additions & 1 deletion chamber/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,10 @@ def fast_distinct(self):
this method provides alternative to the standard distinct method.
:return: qs with unique objects
"""
return self.model.objects.filter(pk__in=self.values('pk'))
qs = self.model.objects.filter(pk__in=self.values('pk'))
if self.query.order_by:
qs = qs.order_by(*self.query.order_by)
return qs

def change_and_save(self, update_only_changed_fields=False, **changed_fields):
"""
Expand Down
14 changes: 14 additions & 0 deletions example/dj/apps/test_chamber/tests/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,20 @@ def test_smart_queryset_fast_distinct(self):
assert_equal(tuple(qs.values_list('pk', flat=True)), (t.pk, t.pk))
assert_equal(qs.fast_distinct().count(), 1)

def test_smart_queryset_fast_distinct_shuld_keep_ordering(self):
TestSmartModel.objects.create(name='a')
TestSmartModel.objects.create(name='b')
TestSmartModel.objects.create(name='c')

assert_equal(
TestSmartModel.objects.order_by('name').fast_distinct().values_list('name', flat=True),
['a', 'b', 'c']
)
assert_equal(
TestSmartModel.objects.order_by('-name').fast_distinct().values_list('name', flat=True),
['c', 'b', 'a']
)

def test_smart_model_first_and_last_with_order(self):
test3 = TestSmartModel.objects.create(name='3')
test2 = TestSmartModel.objects.create(name='2')
Expand Down

0 comments on commit 495faaa

Please sign in to comment.