my models.py:
class Attendancename(models.Model):
teacher_name = models.ForeignKey(Teachername, default='Ram')
date = models.DateField('Date', default=datetime.datetime.today)
intime = models.TimeField('IN-TIME', auto_now=True)
outtime = models.TimeField('OUT-TIME', auto_now=True)
def hours_conversion(self):
startdelta = datetime.timedelta(hours=self.intime.hours, minutes=self.intime.minutes, seconds=self.intime.seconds)
enddelta = datetime.timedelta(hours=self.outtime.hours, minutes=self.outtime.minutes, seconds=self.outtime.seconds)
return (enddelta-startdelta).seconds/3600
def __str__(self):
return "%s" %self.teacher_name
my views.py:
def add_atten(request):
if request.method == 'POST':
form = AttendancenameForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('student:listatten'))
else:
print(form.errors)
else:
form = AttendancenameForm()
return render(request, 'add_atten.html', {'form': form},)
my forms.py:
class AttendancenameForm(ModelForm):
intime = forms.TimeField(input_formats=('%H:%M',))
outtime = forms.TimeField(input_formats=('%H:%M',))
teacher_name = forms.ModelChoiceField(queryset=Teachername.objects.all())
class Meta:
model = Attendancename
fields = ('teacher_name', 'date', 'intime', 'outtime',)
实际上,我尝试根据models.py文件中'intime'
和'outtime'
的差异来计算总小时数,但它会提高到错误率。我想我在做语法错误。任何人都可以告诉我这样做的正确语法或方法是什么?
任何人都请建议我该怎么做才能解决它?
答案 0 :(得分:6)
这是因为您无法从datetime.time
中减去datetime.time
。将它们转换为datetime.datetime
个对象,它将返回一个您可以使用的datetime.timedelta
对象。
If you're lucky enough to be using Django 1.8
, they now have a DurationField
that can be used.
如果不这样做,我建议将timedelta
转换为秒或浮点表示,以便您可以将其实际存储到数据库中。
编辑:在评论中拉了半个答案。
例如 - 如果要存储(整数)秒的数量,可以使用TimeDelta
从secs = td // timedelta(seconds=1)
转换。