Django: how to filter by day/month range without setting the year
I have a course Model but want to add an available period date (optiona) on it, but without concidering the Year.
so I can:
- store 2 dates and wont concidering the years on the Course model
- or store 4 numbers (from_day, from_month, to_day, to_month) on the Course model
First I don't know what is the best solutions (what type of data to store, date or numbers?) Second, I don't know how to filter later with checking the actual date.
If there is a date range in the courses, ex: 2022/12/20 to 2023/01/10, if we are the 2023/01/18, theses courses should be excluded
import datetime
today = datetime.date.today()
def get_available_courses(self):
courses = self.account.get_courses().filter(
...
)
No need to set a year because it should concider any year
When you have a datetime or date object, you can filter using the __month
and __day
options.
Like so:
course1 = Course(
name='Course 1',
start_date='2022-09-01',
end_date='2022-12-31'
)
course2 = Course(
name='Course 2',
start_date='2021-09-01',
end_date='2021-12-31'
)
courses = Course.objects.all()
# below will return both course1 and course2, because the year is not checked.
courses.filter(
start_date__day=1
start_date__month=9,
end_date__day=31,
end_date__month=12
)
Another option, as you mentioned, would be to save the day and month in your database, without a year.
course1 = Course(
name='Course 1',
start_day=1,
start_month=9,
end_day=31,
end_month=12
)
course2 = Course(
name='Course 2',
start_day=1,
start_month=9,
end_day=31,
end_month=12
)
today = datetime.date.today()
courses = Course.objects.all()
# below will return both course1 and course2
courses.filter(
start_day=1,
start_month=9,
end_day=31,
end_month=12
)