Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend Updated March 24, 2020, 2:35 p.m. ⋅ 5236 views

Filtering empty or NULL values in a Django queryset


In Django queryset we have __isnull to check if a value is null.

Here is how we use it:

MyModel.objects.exclude(alias__isnull=True)

 Here were filtering all the values from MyModel model, which have an alias = Null.

To filter out Empty values we can exclude also. Here is how it looks:

MyModel.objects.exclude(alias__isnull=True).exclude(alias__exact='')

exclude allows you to pass multiple arguments, it will the then check for every argument.

MyModel.objects.exclude(some_field=True, other_field=True)

If your query is still more complex, you can use Django's Q Objects.

from django.db.models import Q
MyModel.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

 

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account