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 distinct with *fields #444

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions modeltranslation/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ def _rewrite_applied_operations(self):
if not NEW_RELATED_API:
self._rewrite_where(self.query.having)
self._rewrite_order()
self._rewrite_distinct()
self._rewrite_select_related()

# This method was not present in django-linguo
Expand Down Expand Up @@ -304,6 +305,10 @@ def _rewrite_order(self):
self.query.order_by = [rewrite_order_lookup_key(self.model, field_name)
for field_name in self.query.order_by]

def _rewrite_distinct(self):
self.query.distinct_fields = [rewrite_lookup_key(self.model, field_name)
for field_name in self.query.distinct_fields]

def _rewrite_select_related(self):
if isinstance(self.query.select_related, dict):
new = {}
Expand Down
19 changes: 19 additions & 0 deletions modeltranslation/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2540,6 +2540,25 @@ def test_order_by(self):
self.assertEqual(titles_asc, ('a', 'b', 'c'))
self.assertEqual(titles_desc, ('c', 'b', 'a'))

def test_distinct(self):
"""
Check that field names are rewritten in distinct fields.
This test works only on postgres.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this works only on postgres?

"""
db_engine = django_settings.DATABASES['default']['ENGINE']
if db_engine != 'django.db.backends.postgresql_psycopg2':
return

manager = models.ManagerTestModel.objects
manager.create(title='a')
manager.create(title='b')
manager.create(title='b')
manager.create(title='c')
manager.create(title='c')
manager.create(title='c')
titles = tuple(m.title for m in manager.order_by('title').distinct('title'))
self.assertEqual(titles, ('a', 'b', 'c'))

def test_order_by_meta(self):
"""Check that meta ordering is rewritten."""
manager = models.ManagerTestModel.objects
Expand Down