Federico
Federico

Reputation: 68

filter combined date and time in django

I have a model with separated date and time, I want to filter for future events and ended up writing this, which is not cool. Is there a more nicer way? Can I use combine() and min() in some way for this? As you can see in the query, it must include the today events with time > now

future_events = CauseEvent.objects.filter(cause=instance).exclude(date__lt=datetime.now().date()).exclude(date=datetime.now().date(),
                                                                                                                  time__lt=datetime.now().time()).exists()

Upvotes: 1

Views: 650

Answers (1)

catavaran
catavaran

Reputation: 45595

Lookup using Q objects:

from django.db.models import Q

today = datetime.now().date()
now = datetime.now().time()

future_events = CauseEvent.objects.filter(cause=instance) \
                                  .exclude(Q(date__lt=today) |
                                           Q(date=today, time__lt=now))

Upvotes: 2

Related Questions