简体   繁体   中英

How to filter greater than or is null?

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)

In keeping with the spirit of Willem Van Onsems alternative suggestion

MyModel.objects.exclude(mydatetimefield__lt=mydate)

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 

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

or you can negate the __lt lookup:

from django.db.models import 

MyModel.objects.filter(mydatetimefield__lt=mydate))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM