Objective: I want to have a ModelChoiceFilter rendered on the page where the options/choices for the user to select are the distinct values of a field in the model.
The app allows users to track the cities that they have visited. I want users to be able to filter the model on country and for the filter options to only be countries that are in the model.
I am using django-filters and do successfully have a MultipleChoiceFilter working where the choices work when hard-coded (either in the models.py or in the FilterForm class:
class cityFilter(django_filters.FilterSet):
continent = MultipleChoiceFilter(
choices=cityModel.continent_choices,
widget=forms.CheckboxSelectMultiple,
label='Continent')
class Meta:
model = cityModel
fields = ['city', 'country', 'continent']
One can also set the choices directly in the FilterSet class like this:
country = MultipleChoiceFilter(
choices=(('GB','United Kingdom'),('FR','France')),
widget=forms.CheckboxSelectMultiple,
label='Country'
)
This works okay for continents but I want to allow a filter for countries. I only want to expose to the user the distinct set of countries in the model (as opposed to hard coding every country).
I could do something like this to get all the distinct countries in the model:
country_choices = cityModel.objects.values('country').distinct()
But I'm not sure where this should be placed in the app to get queried on the page load, and would then need to take each value in the queryset and iterate to turn it into a 'choice' tuple.
Is there a better pattern/approach?