pythondjangodjango-modelsdjango-filterdjango-filters

Django_filters check if value/connection 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! :)


Solution

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

    is the solution I found. Just if someone else is struggeling with the same.