Home > database >  Django_filters check if value/connection exists
Django_filters check if value/connection exists

Time:02-02

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! :)

CodePudding user response:

If i understand you, you can use exclude with exact or iexact.

Instead of:

.filter(id_morebio=True)

Try:

.exclude(id_morebio__exact="")

Notice, that there is double underscore __ before exact. It basically will exclude all entries, that have exactly "" as id_morebio value.

CodePudding user response:

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.

  •  Tags:  
  • Related