Reputation: 231
I have a course Model but want to add an available period date (optiona) on it, but without concidering the Year.
so I can:
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
EDIT:
I tried a solution and I tought it worked but it doesn't : I have 2 situation:
When the date range isn't crossing the new year (that one is working "filter_not_year_crossed")
When the date range is crossing the new year: "filter_year_crossed" (that one isn't done yet, I didn't found yet how)
today = datetime.date.today()
today_day = today.day
today_month = today.month
# we are by exemple the 15/02
today_day = 15
today_month = 2
filter_not_year_crossed = (
# CHECK END
Q(available_end_at__month__lt=today_month) |
(Q(available_end_at__month=today_month) &
Q(available_end_at__day__gte=today_day))
# CHECK START
) & (Q(available_start_at__month__lt=today_month) |
(Q(available_start_at__month=today_month) &
Q(available_start_at__day__lte=today_day)))
filter_year_crossed = ( <=== HERE
Q(available_end_at__month=today_month) &
Q(available_end_at__day__gte=today_day)
)
is_year_crossed =
(Q(available_end_at__month__lt=F('available_start_at__month')) |
Q(available_end_at__month=F('available_start_at__month'),
available_end_at__day__lt=F('available_start_at__day')))
filter_end = Q(available_start_at__isnull=True,
available_end_at__isnull=True) | (
(is_year_crossed & filter_year_crossed) | (~is_year_crossed
& filter_not_year_crossed)
)
courses = courses.filter(filter_end)
Upvotes: 0
Views: 156
Reputation: 566
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
)
Upvotes: 1