carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections
https://django-filter.readthedocs.io/en/main/
Other
4.46k stars 769 forks source link

Empty choice in ModelMultipleChoiceFilter #1435

Closed primoz-k closed 3 years ago

primoz-k commented 3 years ago

I'm trying to implement a filter which uses ModelMultipleChoiceFilter on a ForeignKey field (I would like to filter objects by multiple ForeignKey objects with OR relation).

But in the resulting DOM element, there is no empty field like there is on a ModelChoiceFilter. Is this intentional?

Code example:

# Models
class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    mentor = models.ForeignKey('users.User', on_delete=models.SET_NULL, verbose_name='Mentor', null=True, blank=True)
# Filter
class PersonFilter(django_filters.FilterSet):
    mentor__id = django_filters.ModelMultipleChoiceFilter(queryset=Person.objects.all())

    class Meta:
        model = Person
        fields = ['mentor__id']

The resulting dropdown does not have -------------- as an option.

carltongibson commented 3 years ago

You're looking for null_value https://django-filter.readthedocs.io/en/stable/ref/filters.html?highlight=null_value#choicefilter

But also see https://django-filter.readthedocs.io/en/stable/ref/settings.html