我想从其他模型中自动填充模型,因为每次我认为愚蠢时都会创建新实例TimeDay。 我有3个型号:
CHOICE_DAYWEEK = ((1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'))
CHOICE_TIME = ((6, '6:00'), (7, '7:00'), (8, '8:00'), (9, '9:00'))
class Day(models.Model):
day = models.IntegerField(choices=CHOICE_DAYWEEK)
def __unicode__(self):
return self.day
class Time(models.Model):
time = models.IntegerField(choices=CHOICE_TIME)
def __unicode__(self):
return self.time
class TimeDay(models.Model):
day = models.ForeignKey(Day, on_delete=models.CASCADE)
time = models.ForeignKey(Time, on_delete=models.CASCADE)
entry = models.ForeignKey(Entry, blank=True, null=True, on_delete=models.CASCADE)
def __unicode__(self):
return '{} {}'.format(self.day.day, self.time.time)
我想自动填充模型TimeDay,例如:
TimeDay(id=1, day=1, time=6, entry=None)
TimeDay(id=2, day=1, time=7, entry=None)
...
TimeDay(id=4, day=1, time=9, entry=None)
...
TimeDay(id=12, day=3, time=9, entry=None)
如果没有管理员网站并手动创建实例,我该如何做到这一点?
答案 0 :(得分:0)
您应该使用DateTimeField
进行验证,而不是按照以下方式编写单独的模型:
def validate_date(value):
if not value.weekday() not in [0, 1, 2]:
raise ValidationError("Day should be a Monday, Tuesday or Wednesday")
# similarly implement validation for time
if value.hour not in [6, 7, 8, 9] or value.minute != 0:
raise ValidationError("Invalid Time")
class TimeDay(models.Model):
...
time = models.DateTimeField(validators=[validate_date])
...