如何过滤大于或为空?

If I want to filter "greater than or equal to", I can use gte:

MyModel.objects.filter(mydatetimefield__gte=mydate)

Likewise, if I want to filter "is none/null", I can use isnull:

MyModel.objects.filter(mydatetimefield__isnull=mydate)

How can I combine these to filter for "greater than or equal to or is null", so the above filter would return both objects if i) mydatetimefield >= mydate, and ii) mydatetimefield == null?

评论
深深小安
深深小安

you use Q statements to perform OR logic

from django.db.models import Q

qry = Q(mydatetimefield=None) | Q(mydatetimefield__gte=mydate)

MyModel.objects.filter(qry)

与Willem Van Onsems的精神保持一致

MyModel.objects.exclude(mydatetimefield__lt=mydate)
点赞
评论
fharum
fharum

You can use Q objects [Django-doc], and use a bitwise or (|) operator to specify a condition that should satisfiy one of the two subconditions:

from django.db.models import Q

MyModel.objects.filter(
    Q(mydatetimefield__gte=mydate) |
    Q(mydatetimefield=None)
)

or you can negate the __lt lookup:

from django.db.models import Q

MyModel.objects.filter(~Q(mydatetimefield__lt=mydate))
点赞
评论