Django_filters checkbox if value exists

Hej!

I’m looking for an option on how to filter IF the value exists, the value itself is irrelevant. To filter all institutions with the given AddOn.

A checkbox would be best where I can ‘check’ if I want my database entries filtered by this variable or not.
If it’s ‘checked’ I want to filter all entries which have the given variable and if it’s not checked I don’t want to filter.

models.py

class Institution(models.Model):
    name = models.CharField(
        verbose_name=_("Name of the institution"),
        max_length=200,
    )
    abbreviation = models.CharField(  # null=False, but "" allowed. Is Django convention
        verbose_name=_("Acronym"),
        max_length=25,
        blank=True,
        help_text=_("if applicable"),
    )

class AddInstitutionMorebio(models.Model):
    institution = models.OneToOneField(
        Institution,
        on_delete=models.PROTECT,
        related_name="institution_morebio"
    )
    id_morebio = models.CharField(
        max_length=6,
        unique = True
    )
filters.py

class InstitutionFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(method='name_filter', label="Name")

   morebio_id = AddInstitutionMorebio.objects.filter(id_morebio=True)  # this does nothing

Does someone know what to do?
Any help is appreciated! :slight_smile:

I think you could create a BooleanFilter that has a lookup_expr set to isnull and the field_name set to name. See the reference docs for filters. Depending on how you write it, you may need the also use the exclude argument.

1 Like

You wrote:

The field always exists in every instance of the model.

Are you saying to want to check to see if the value is null?
If so, see the isnull lookup.

But for some reason, I think I’m misunderstanding what you’re looking for here. Can you perhaps elaborate more on what you’re trying to achieve?

Not all users can see the AddOn. But you are right. In the database the field/variable always exists.
I want to filter only those fields who have a value (not null) for the given variable.

So I want to see if it’s not null and give me those.

So yes, you would use the isnull lookup clause in your filter.
e.g. SomeModel.objects.filter(field_name__isnull=False)

1 Like

Thanks!
And thanks for the link to the documentation. I just couldn’t find it.

morebio_id = BooleanFilter(lookup_expr='isnull', field_name='institution_morebio__id_morebio', label='MoreBio')

is the solution fo me :slight_smile:

1 Like