如何根据自定义营业时间确定最近的上一个工作日?
对于一个有自定义营业时间和事件的商家,我需要找出每个事件(比如一周内的事件)最近的上一个营业日。举个例子,假设一个商家在星期天、星期三、星期五和星期六营业。现在有一个事件是在2011年6月22日星期三下午3点开始的,我该如何快速确定2011年6月19日星期天是这个事件最近的上一个营业日呢?以下是相关的模型:
class Business(models.Model):
name = models.CharField(max_length=50)
class BusinessHours(models.Model):
"""
I realize there are better ways to store business hours,
but this approach is simple and serves my purposes for now.
However, if another schema solves the problem above more efficiently,
feel free to make a suggestion.
"""
business = models.ForeignKey(Business)
sunday_open = models.TimeField(blank=True, null=True)
sunday_close = models.TimeField(blank=True, null=True)
monday_open = models.TimeField(blank=True, null=True)
monday_close = models.TimeField(blank=True, null=True)
... continue for each day ...
class Event(models.Model):
business = models.ForeignKey(Business)
start = models.DateTimeField()
end = models.DateTimeField()
我假设大部分工作需要在Python中完成,除了Django的部分,所以如果Django的模型让解决方案变得复杂,可以忽略它。如果需要更多信息,我很乐意提供。提前谢谢你们!
1 个回答
3
你可能想用Python对你的数据库进行查询。我建议你看看Django文档,了解如何进行数据库查询,还有附录里的字段查找。
基本的格式可能看起来像这样:
# Will return a list of dictionary objects for all rows with that foreign key
# Ex: [{'business' : '3', 'monday_open' : someTime, 'monday_close' : someTime...},...]
storeHours = BuisnessHours.objects.values().filter(business = *foreign key*)
# You can also get your even like this
# Ex: [{'business' : '3', 'start' : someTime, 'end' : someTime}, {'business' : '3'...]
storeEvent = Event.objects.values().filter(business = *same foreign key as above*)
*注意,如果你想为每个商店保存不同的事件,最好在事件模型中添加一个'名称'列,这样你就可以根据特定事件进行查询。此外,建议使用DateTimeField而不是TimeField,这样你也可以保存日期。
当你拿到查询结果后,在Python中将开始和结束时间分组应该很简单,你可以查看哪些时间最接近事件的范围。为此,我建议你也看看datetime模块。
我还建议你看看这个问题。他在查询格式中使用了列表推导,做了一些很有趣的事情。
不过,可能还有更有效的方法可以通过字段查找来实现,所以我也建议你研究一下这个。