[Answered ]-Comparing day ranges with Django

2👍

Given the used schema I would propose:

Deal.objects.filter(
  Q(deal_day_start__lte=current_day, deal_day_end__gte=current_day) | 
  Q(deal_day_start__lte=current_day, deal_day_end__lt=F("deal_day_start")) | 
  Q(deal_day_start__gte=current_day, deal_day_end__gte=current_day, deal_day_end__lt=F("deal_day_start"))
)

Let’s make the observation that for a deal to wrap the end day must be smaller than the start day. We have 3 cases for current day to belong to a deal period:

  • If the current day is between start and end day.
  • If the current day is greater than the start day but greater that the end day, then it means that the deal must wrap.
  • If the current day is smaller than the start date, then the deal must wrap. But not only wrap but also finish after the current day.

Leave a comment