Django filter using DateTimeField that can be null

Question:

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

Asked By: B. Mohammad

||

Answers:

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")
Answered By: Sorin Burghiu

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))
Answered By: 0sVoid

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")
Answered By: Balizok
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.