Added distinct test (ref
@@ -699,7 +699,6 @@ class FallbackTests(ModeltranslationTestBase):
class FileFieldsTest(ModeltranslationTestBase):
-
def tearDown(self):
if default_storage.exists('modeltranslation_tests'):
# With FileSystemStorage uploading files creates a new directory,
@@ -3008,6 +3007,51 @@ class TestManager(ModeltranslationTestBase):
self.assertEqual(inst.titlea, 'title_a')
self.assertEqual(inst.titleb, 'title_b')
+ def test_distinct(self):
+ """Check that field names are rewritten in distinct keys."""
+ manager = models.ManagerTestModel.objects
+ manager.create(
+ title_en='title_1_en', title_de='title_1_de',
+ description_en='desc_1_en', description_de='desc_1_de')
+ manager.create(
+ title_en='title_1_en', title_de='title_1_de',
+ description_en='desc_2_en', description_de='desc_2_de')
+ manager.create(
+ title_en='title_2_en', title_de='title_2_de',
+ description_en='desc_1_en', description_de='desc_1_de')
+ manager.create(
+ title_en='title_2_en', title_de='title_2_de',
+ description_en='desc_2_en', description_de='desc_2_de')
+
+ # Without field arguments to distinct() all fields are used to determine
+ # distinctness, therefore when only looking at a subset of fields in the
+ # queryset it can appear that there are duplicates (the titles in this case)
+ titles_for_en = tuple(m.title for m in manager.order_by('title').distinct())
+ with override('de'):
+ titles_for_de = tuple(m.title for m in manager.order_by('title').distinct())
+
+ self.assertEqual(titles_for_en, ('title_1_en', 'title_1_en', 'title_2_en', 'title_2_en'))
+ self.assertEqual(titles_for_de, ('title_1_de', 'title_1_de', 'title_2_de', 'title_2_de'))
+
+ # On PostgreSQL only, distinct() can have field arguments (*fields) to specify which fields
+ # the distinct applies to (this generates a DISTINCT ON (*fields) sql expression).
+ # NB: DISTINCT ON expressions must be accompanied by an order_by() that starts with the
+ # same fields in the same order
+ if (django_settings.DATABASES['default']['ENGINE'] ==
+ 'django.db.backends.postgresql_psycopg2'):
+ titles_for_en = tuple(
+ (m.title, m.description) for m in manager.order_by(
+ 'title', 'description').distinct('title'))
+ with override('de'):
+ titles_for_de = tuple(
+ (m.title, m.description) for m in manager.order_by(
+ 'title', 'description').distinct('title'))
+
+ self.assertEqual(
+ titles_for_en, (('title_1_en', 'desc_1_en'), ('title_2_en', 'desc_1_en')))
+ self.assertEqual(
+ titles_for_de, (('title_1_de', 'desc_1_de'), ('title_2_de', 'desc_1_de')))
+
class TranslationModelFormTest(ModeltranslationTestBase):
def test_fields(self):
