Django Filters

Hello how to filter a models by weeks of the month? Let say i want to filter the month of January, and i only need to get the first week of January, what would be the possible filtering? Thank you

Test.objects.filter(date_from__year=2021, date_from__month=1)

What specifically do you mean by “first week of January”? Are you talking about Jan 1-7? Or are you talking about the first week that includes January (Dec 27 - Jan 2 for 2021)? Or are you talking about the first full week of January (Jan 3 - Jan 9)?

And you mention the general case - “how to filter by weeks of the month”, can you elaborate that a little based on the previous questions?

(Yes it does matter, because other than the case where “the first week of January” being defined as Jan 1-7, the specification for “week of the month” needs to account for the days of the week.)

Let say in the month of April, in week-1 dates will start from April 1 to April 7, then week-2 would be April 8 to April 14, week-3 would be April 15 to April 21, then April 22 to April 28 for week-4. But there is still 2 remaining days because the end date of April is 30. My question now is, how can i get the April 1, 2, 3, 4, 5, 6, and 7 in week one? Then April 8, 9, 10, 11, 12, 13, 14 in week two, and etc.?

week_one_x = datetime.today().replace(day=1)
week_one_y = datetime.today().replace(day=7)

I think the above code will not work, when the dates is dynamic.

Test.objects.filter(
     date_from__year=2021, 
     date_from__month=1,
     date_from__day__gte=[week_one_x, week_one_y]
)

Also, simple filtering like this on django will not work either?

See the range operator for queries. Construct your range as the start date and end date of that range.
(Note: See the note on that page if you’re working with datetime fields instead of date fields, there is a difference.)

1 Like

That doesn’t help him with his particular case - the extractweek function works on the ISO-8601 definition of a week, which is not what he’s looking for. See ISO week date - Wikipedia (It’s why my first reply was asking for clarification of his definition of a “week”.)

Also, the link you posted isn’t a valid link. Clicking on it gives a 404. There should be a hyphen between “database” and “functions” The correct link is: Database Functions | Django documentation | Django

1 Like

I found this solution and i think this will do,

    year = datetime.today().year
    month = datetime.today().month
    current_calendar = calendar.monthcalendar(year, month)

    print(current_calendar)
    # [[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 0, 0]]