Rajan Kumar

rajan

Founder & Programmer at HackersFriend Updated March 24, 2020, 2:35 p.m. ⋅ 105 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=''))

 

 



arrow_upward Upvote

comment Comment

arrow_downward downvote



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details