[Django]-Django ORM: checking if a field is blank or filled

0👍

You can check is a field is blank or not by isnull

YourModel.objects.filter(title__isnull=True)

This will return all the objects which have no title.

3👍

So for this, the Django docs around querysets and q objects will be your friend.

Checking if something is null or '' (empty) is a little tricky at first but once you understand SQL and Django ORM it will get easier.

The first point to make is null != '' in SQL they are two different values. The two previous answers to this post are incorrect as they did not read your question.

Basically there are three checks you could be performing depending on use case,

  1. Is a result empty – YourModel.objects.filter(title='')
  2. Is a result null – YourModel.objects.filter(title__isnull=True)
  3. Is a result null or empty (using Q objects) – YourModel.objects.filter(Q(title='') | Q(title__isnull=True))

In your case, you will want option 3 as you are asking for a result set which shows null and empty values in a result set.

Example:

#  models.py
class TestModel(models.Model):
    a = models.CharField(max_length=10, blank=True, null=True)

#  code
TestModel.objects.create() # id: 0
TestModel.objects.create(a='') # id: 1
TestModel.objects.create(a='a value') # id: 2

# option 1 above
TestModel.objects.filter(a__isnull=True)
#> <QuerySet [<TestModel: TestModel object (1)>]>

#option 2 above
TestModel.objects.filter(a='')
#> <QuerySet [<TestModel: TestModel object (2)>]>

#option 3 above
from django.db.models import Q
TestModel.objects.filter(Q(a='') | Q(a__isnull=True))
#> <QuerySet [<TestModel: TestModel object (1)>, <TestModel: TestModel object (2)>]>

-1👍

I am trying to check if title filed is filled or blank, how can i achieve this?

blank is not a value. Blank means the field is not required in a form (it will not show up). Usually if blank=True, then null=True as well (or you need to provide an explicit default).

You can use None which is Python’s equivalent of NULL, like:

MyModel.objects.filter(title=None)

or you can make it more explicit by using the __isnull [Django-doc] lookup:

MyModel.objects.filter(title__isnull=True)

Leave a comment