我的表格中有 2 个DateField
,start_date
和end_date
以及一个名为duration
的FloatField
。我想出如何通过计算开始和结束日期的持续时间来自动保存没有用户输入的持续时间,但是我如何给出跳过周末和任何特定公共假期的条件?
model.py:
class Leave(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+')
start_date = models.DateField()
end_date = models.DateField()
duration = models.FloatField(null=True, blank=True)
form.py:
class LeavesDetailForm(forms.ModelForm):
class Meta:
model = Leave
fields = ('employee', 'start_date', 'end_date', 'duration')
widgets = {'start_date': forms.DateInput(attrs={'type': 'date'}),
'end_date': forms.DateInput(attrs={'type': 'date'}),
'employee': forms.HiddenInput(),
'duration': forms.HiddenInput()}
view.py:
def my_leaves_view(request):
"""
My Leaves view
:param request:
:return:
"""
form = LeavesDetailForm(request.POST or None)
if form.is_valid():
inst = form.save(commit=False)
inst.start_date = form.cleaned_data['start_date']
inst.end_date = form.cleaned_data['end_date']
duration = (inst.end_date - inst.start_date).days
inst.duration = duration
inst.save()
return HttpResponseRedirect('/hrm/employee/leaves')
return render(request, 'hrm/employee/details/my_leaves.html', context)
一个可能的解决方案是使用numpy
的busday_count
函数:
import numpy as np
def my_leaves_view(request):
...
inst.duration = np.busday_count(inst.start_date, inst.end_date)
...
这准确地给出了没有周末和节假日的日子数。