Search code examples
python-3.xdjango-2.1

Django date filter - find a date in-between


I'm attempting to create a query that returns an event if it runs at any point in a given period of time between 2 dates.

model:

class MyModel(models.Model):
    start_date = models.DateField(auto_now=False, blank=True, null=True, verbose_name="Start date")
    hd_end_date = models.DateField(blank=True, default=None, null=True, verbose_name="End date") 

Current code to try and filter:

        import calendar
        max_day = calendar.monthrange(year, month)[1]

        start = "{}-{}-01".format(year, month)
        end = "{}-{}-{}".format(year, month, max_day)

        # If the event starts in the month, or if it ends in the month
        filter.append(Q(start_date__range=[start, end]) |
                      Q(hd_end_date__range=[start, end]))

My models have a start_date and an end_date (hd_end_date). This logic appeared to work as intended at first. However there is problem and I know what is, just not how to solve it.

For example if my event model starts in December and finishes in February the above code would return an event for December and in February but it wouldn't return one for January as it neither starts or ends in that month. How can I adjust this code so that it would return an event that run over multiple months.


Solution

  • Appears I was over thinking it, and resolved the issue by simplifying.

    filter.append(Q(start_date__month__lte=month, hd_end_date__month__gte=month))

    I realised that I could just look at the month and didn't need to range the dates, as all I wanted to know is that the event ran on that month between it's start and end date.