Reputation: 3492
Having some abstract model with field date
:
class MyModel(models.Model):
date = models.DateField(null=True)
...
How do I compose a filter query that returns all records where date
field is either Null
or is in range of given dates?
This is what I've tried so far but I'm always getting empty queryset:
_ = MyModel.objects.filter(Q(date__isnull=True) & Q(date__range=[...])
Upvotes: 1
Views: 45
Reputation: 476557
You need to use a logical or here, not an and, so with |
instead of &
:
MyModel.objects.filter(Q(date__isnull=True) | Q(date__range=[…])
or you can simplify this to:
MyModel.objects.filter(Q(date=None) | Q(date__range=[…])
By using a logical and, you want to retrieve MyModel
s where the data
-field is both NULL
and in the range of …
for the same record. No value is NULL and in the range at the same time.
Upvotes: 1