class Session(models.Model):
tutor = models.ForeignKey(User)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
始终阻止start_time
重叠end_time
的最佳方法是什么?
答案 0 :(得分:1)
首先,您应该在表单级别执行此操作,有关如何执行此操作的说明,请参阅Cleaning and validating fields that depend on each other,它将如下所示:
def clean(self):
cleaned_data = super(YourForm, self).clean()
if cleaned_data['start_time'] > cleaned_data['end_time']:
raise forms.ValidationError(_(u'Start time must be before end time'))
此外,您可以在保存方法或pre_save signal中以较低级别强制执行此操作:
from django.db.models import signals
class StartTimeAfterEndTimeException(Exception):
def __init__(self, model):
super(StartTimeAfterEndTimeException, self).__init__(
'Start time %s should not be after end time %s' % (
model.start_time, model.end_time))
def session_force_end_time(sender, instance, **kwargs):
if instance.start_time >= instance.end_time:
raise StartTimeAfterEndTimeException(instance)
signals.pre_save.connect(session_force_end_time, sender=Session)
但这个级别很低,所以用户不友好。