Django: getting data where the date and time is greater than now

I have a model that describes such an event:

class Event(models.Model): date = models.DateField() time = models.TimeField() 

I would like to get all future events (i.e. date is greater than now.date() ). However, if the date is today, I would like to receive today's events with a time greater than now.time() .

This is what I do:

 events = Event.objects.filter(date__gte=now.date()).filter(time__gte=now.time()).order_by('-date') 

where now = datetime.datetime.now()

But this is wrong, because it gives me an empty set if the only event is tomorrow, and its time is less than the current time (for example, if the event is tomorrow at 09:00 and today - 19:00)

is this possible in django?

PS: I would like to avoid repeating through a set.

+6
source share
1 answer

Use Q objects that allow you to make queries with OR statements.

 from django.db.models import Q Events = Event.objects.filter(Q(date=now.date(),time__gte=now.time())|Q(date__gt=now.date())).order_by('-date') 

Please note that you can sort in the time field:

 order_by('-date', '-time') 
+9
source

Source: https://habr.com/ru/post/909902/


All Articles