I am using django-select2 with forms for creating a drop-down list, using ModelSelect2Widget.
My problem is that I filter on the field 'name' and several objects can have the same 'name' but different 'value' (see model description below). This leads to the same name appearing several times in the dropdown menu.
I would like to remove these duplicates. I tried to use .distinct('name') for selecting the queryset, but it doesn't seem to work. example of result obtained with ModelSelect2Widget
Below is the description of the code I use:
I have two models linked by a foreign key
models.py
class Who(models.Model):
name = models.CharField(max_length=256)
value = models.CharField(max_length=256)
def __str__(self);
return str(self.name)
class Data(models.Model):
who = models.ForeignKey(Who)
And I use the form described here:
forms.py
from django_select2.forms import ModelSelect2Widget
...
class CreateDataForm(ModelForm):
class Meta:
model = Data
fields = ('who',)
widgets = {'who': ModelSelect2Widget(
queryset=Who.objects.all().distinct('name'),
search_fields=['name_icontains']
)}
Does anyone know how I could remove these duplicates?