Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

title = models.ForeignKey(blank=True, null=True)

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


1 Answers

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

like image 197
Matt Seymour Avatar answered Oct 18 '25 22:10

Matt Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!