Search code examples
djangofilterdjango-filter

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


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!


Solution

  • 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)