diff --git a/advanced_filters/tests/test_views.py b/advanced_filters/tests/test_views.py index 2e23c2b..593cf7c 100644 --- a/advanced_filters/tests/test_views.py +++ b/advanced_filters/tests/test_views.py @@ -100,6 +100,14 @@ def test_database_choices(self): def test_more_than_max_database_choices(self): factories.Client.create_batch(5, assigned_to=self.user) view_url = reverse(self.url_name, kwargs=dict( - model='customers.Client', field_name='first_name')) + model='customers.Client', field_name='id')) res = self.client.get(view_url) self.assert_json(res, {'results': []}) + + @override_settings(ADVANCED_FILTERS_MAX_CHOICES=4) + def test_distinct_database_choices(self): + factories.Client.create_batch(5, assigned_to=self.user, email="foo@bar.com") + view_url = reverse(self.url_name, kwargs=dict( + model='customers.Client', field_name='email')) + res = self.client.get(view_url) + self.assert_json(res, {'results': [{'id': 'foo@bar.com', 'text': 'foo@bar.com'}]}) diff --git a/advanced_filters/views.py b/advanced_filters/views.py index d3e3d35..58cf78a 100644 --- a/advanced_filters/views.py +++ b/advanced_filters/views.py @@ -69,9 +69,8 @@ def get(self, request, model=None, field_name=None): logger.debug('No choices calculated for field %s of type %s', field, type(field)) else: - choices = model_obj.objects.values_list(field.name, flat=True) - if choices.count() < max_choices: - choices = set(choices) + choices = model_obj.objects.values_list(field.name, flat=True).distinct() + if choices.count() <= max_choices: choices = zip(choices, choices) logger.debug('Choices found for field %s: %s', field.name, choices)