Django After Midnight Business Hours TimeField Comparison Error
I have business hours that I need to compare and I am getting incomplete results if business hours pass midnight.
My model
class Hours(models.Model):
dayofweek = models.ForeignKey('Dayofweek')
opentime = models.TimeField(blank=True, null=True)
closetime = models.TimeField(blank=True, null=True)
...
If I just need to display the clock, everything works fine: Saturday from 17:00 to 2:00
Now, when I try to query the hours to check if the business is open, those who passed after midnight will return False
for exists()
:
my request
if Hours.objects.filter(
business__id=id,
dayofweek__pyday=dt,
opentime__lte=mytime,
closetime__gte=mytime).exists():
#do something
Any suggestions on how to tell Django that 2am is after 5pm?
source to share
A day can have multiple periods, but it doesn't matter, the day ends at 23:59. If this continues the next day, you will have to split the time slots. So the logic of your filters will be like this ...
# Spans over 2 days
if opentime > closetime:
Hours.objects.filter(
business_id=id,
dayofweek_pyday=dt,
opentime_tye=myOpenTime,
closetime_gte=11:59:99
).exists() ||
Hours.objects.filter(
business_id=id,
# Next date
dayofweek_pyday=dt + 1,
opentime_tye=00:00:00,
closetime_gte=myCloseTime
).exists()
# Spans over 1 day
else:
Hours.objects.filter(
business__id=id,
dayofweek__pyday=dt,
opentime__lte=myOpentime,
closetime__gte=myClosetime).exists()
I don't know django, so this is just some pseudocode and an alternative approach that I would use.
source to share
How about using the F and Q expressions across two queries:
one for a simple case (opening time <= closing time)
Hours.objects.filter(
opentime__lte=F('closetime'),
business__id=id,
dayofweek__pyday=dt,
opentime__lte=mytime,
closetime__gte=mytime).exists():
and one for the odd case (closing time and opening time)
Hours.objects.filter(
opentime__gt=F('closetime'),
business__id=id,
dayofweek__pyday=dt,
Q(opentime__lte=mytime) | Q(closetime__gte=mytime)).exists():
source to share