在给定的自定义工作时间的情况下,如何确定活动的最近的上一个工作日?

问题描述

| 对于具有自定义BusinessHours和Events的给定业务,我需要弄清楚如何获取每个事件的最近的上一个工作日(例如,一个星期的事件)。例如,假设某公司在周日,周三,周五和周六都有BusinessHours。假设有一个活动从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()
我假设除了Django之外,大部分工作都需要在python中进行,因此如果使解决方案复杂化,请忽略Django模型。如果需要,我很乐意提供其他信息。提前致谢!     

解决方法

        您将要查询以python编写的数据库。我会查看有关如何进行数据库查询的django文档以及fieldlookups的附录。 基本格式可能类似于:
# 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*)
*请注意,如果您要为每个商店保存不同的事件,则在事件模型中使用\'name \'列可能会很好,这样您还可以基于某个事件进行查询。另外,也可以尝试使用DateTimeField而不是使用TimeField,这样您也可以保存日期。 返回查询字典后,应该很简单地在python中对开始时间和结束时间进行分组,看看哪些时间最接近事件范围。为此,我还将看一下datetime模块。 我也将看看这个问题。他使用查询格式的列表理解功能做了一些非常有趣的事情。 不过,也许有一种更有效的方法可以简单地通过fieldlookups做到这一点,所以我也将对此进行研究。