B. Mohammad
B. Mohammad

Reputation: 2464

Django filter using DateTimeField that can be null

I want to filter a table objects using a DateTimeField => last_user_action_time, this field can be null so I need the cases where its null to be included in the result.

Here is what I tried:

notification_objects = SinglePushNotification.objects.filter(
            last_user_action_time__lte=day_start,
            last_user_action_time__isnull=True,
        ).select_related("customer")

This return an empty querySet knowing there is objects where null=True

Upvotes: 0

Views: 1595

Answers (3)

Balizok
Balizok

Reputation: 1065

Even though the method in the other answers work, I still want to suggest another way of achieving what you want.

That is, instead of checking if any of the conditions are true, you could just exclude the case where none of them are:

notification_objects = SinglePushNotification.objects.exclude(
            last_user_action_time__gt=day_start
        ).select_related("customer")

Upvotes: 2

0sVoid
0sVoid

Reputation: 2663

The .filter() function joins queries together with AND and not OR - so your current filter is looking for last_user_action_time fields that equal day_start AND isnull=True. You should use a Django Q() object.

# e.g.
.filter(Q(last_user_action_time__lte=day_start) | Q(last_user_action_time__isnull=True))

Upvotes: 1

Sorin Burghiu
Sorin Burghiu

Reputation: 779

Sounds like you need to use an or query, in your attempt you are checking that both conditions are true: field is null and date is less than start (impossible case).

Try an or like so:

from django.db.models import Q

notification_objects = SinglePushNotification.objects.filter(
            Q(last_user_action_time__lte=day_start) |
            Q(last_user_action_time__isnull=True)
        ).select_related("customer")

Upvotes: 1

Related Questions