[Answer]-Selecting event within date span in Django

1👍

Try it like this:

events = Event.objects.filter(
         Q(schedules__from_date__gte=from_date) | Q(schedules__to_date__gte=from_date), 
         Q(schedules__to_date__lte=to_date) | Q(schedules__from_date__lte=to_date))
events = events.distinct()

Hope it helps!
For a full explanation on the Q class you can see the docs here

As for the logic, what we are doing is getting the events whose schedules START or FINISH after our “from date”. If it started after, we need the START or FINISH date to be lower than our “to date”. If it started before, we need it to finish in the interval, so it will satisfy the condition too.

It is kinda complicated to explain, I will elaborate better later!

👤Alvaro

Leave a comment