title = models.ForeignKey(blank=True, null=True)
I am trying to check if title filed is filled or blank, how can i achieve this?
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,
YourModel.objects.filter(title='')
YourModel.objects.filter(title__isnull=True)
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)>]>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With