Joao Lucas
Joao Lucas

Reputation: 95

Check if any date in a range is between another range

I have the following situation:

This is my views.py:

def home(request):

    date = datetime.date.today()
    start_week = date - datetime.timedelta(date.weekday() + 1)
    end_week = start_week + datetime.timedelta(6)
    week_tasks = Task.object.filter(owner=request.user, start_date__range=[start_week, end_week])
    context = {}
    context['week_tasks'] = week_tasks
    return render(request, 'home.html', context)

This view check if the start_date (DateField) is inside the range of the current week. But I have another field on the database, end_date, and I want to check if any value of this range is on the current week.

Check the exemple:enter image description here Let's supose that the current week is the week of the day 17. With my current view, only the All Day Event and Conference belong to the week. I need to show that all these events belong to the week.

Obs.: I can't just check if start_date and end_date are in the week, because I have the situation of the Long Event, that starts before the week and ends after.


WORKING:

views.py:

def home(request):

    date = datetime.date.today()
    if date.isoweekday() == 7:
        date = date + datetime.timedelta(1)
    start_week = date - datetime.timedelta(date.isoweekday())
    end_week = start_week + datetime.timedelta(6)
    week_tasks = Task.object.filter(owner=request.user).exclude(end_date__lt=start_week).exclude(start_date__gt=end_week)
    context = {}
    context['week_tasks'] = week_tasks
    return render(request, 'home.html', context)

Upvotes: 2

Views: 2230

Answers (1)

Serbitar
Serbitar

Reputation: 2224

week window is defined by: week_start, week_end

tasks are defined by: task_start, task_end

task has overlap with week if:

task_start < week_end and task_end >= week_start

Upvotes: 6

Related Questions