Home > Net >  Is there a simpler way check if the filter i am filtering by is NULL in django?
Is there a simpler way check if the filter i am filtering by is NULL in django?

Time:10-28

I am wondering whether there is a simpler way to ignore NULL values when filtering in django. I don't mean NULL values in the database but rather potential NULL values I am filtering by. This is my code so far:

        if data['grade'] is not None:
            posts = posts.filter(grade=data['grade'])
        if data['subject'] != '':
            posts = posts.filter(subject=data['subject'])

Is there a way to avoid all the if clauses and write the filter in a single statement? Thanks in advance!

CodePudding user response:

from django.db.models import Q

MyModel.objects.filter(~Q(grade__isnull=False) & ~Q(subject__exact=''))

edit:

you can take the idea from this here Django Filter Model by Dictionary

or you can make a copy from your data

for i in data.copy():
        if data[i] == "" or data[i] == None:
            data.pop(i)

or

for i in data.copy():
        if not data[i]:
            data.pop(i)

after that MyModel.objects.filter(**data)

  • Related