Stan Reduta
Stan Reduta

Reputation: 3492

Filter queryset by field with multiple options

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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 MyModels 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

Related Questions