Django - 营业时间的对象

时间:2012-08-31 13:52:04

标签: django django-models django-forms

我正在尝试模拟公司一周的营业时间。这是我的尝试:

class Company(models.Model):
    name = models.CharField(max_length=100)
    logo = models.FileField(upload_to='company_logos')
    mon_start = models.TimeField()
    mon_end = models.TimeField()
    tue_start = models.TimeField()
    tue_end = models.TimeField()
    wed_start = models.TimeField()
    wed_end = models.TimeField()
    thu_start = models.TimeField()
    thu_end = models.TimeField()
    fri_start = models.TimeField()
    fri_end = models.TimeField()
    sat_start = models.TimeField()
    sat_end = models.TimeField()
    sun_start = models.TimeField(blank=True)
    sun_end = models.TimeField(blank=True)

这看起来是否正确?

是否有更动态的方式来定义它?

我可以轻松验证每一天(在表单上)吗?

1 个答案:

答案 0 :(得分:16)

从@lyapun的建议来看,对我来说可接受的解决方案是:

WEEKDAYS = [
  (1, _("Monday")),
  (2, _("Tuesday")),
  (3, _("Wednesday")),
  (4, _("Thursday")),
  (5, _("Friday")),
  (6, _("Saturday")),
  (7, _("Sunday")),
]


class Company(models.Model):
    name = models.CharField(
        max_length=100
    )
    logo = models.FileField(
        upload_to='company_logos'
    )



class OpeningHours(models.Model):
    store = models.ForeignKey(
        Company
    )
    weekday = models.IntegerField(
        choices=WEEKDAYS,
        unique=True
    )
    from_hour = models.TimeField()
    to_hour = models.TimeField()