此示例是当您将 django 项目作为 API 制作时
您可以 使用使用SCIPY的Numpy获得工作日(查看更多详细信息)您必须通过numpy
pip
蟒蛇 2.7
pip install numpy
蟒蛇 3
pip3 install numpy
根据models.py
您要放置属性方法的位置添加:
class WorkingDay(models.Model):
# YY-MM-DD
start = models.DateField(null=True, verbose_name="start")
end = models.DateField(null=True, verbose_name="end")
@property
def workdays(self):
total = np.busday_count(self.start, self.end)
return total
然后在你的serializers.py
你可能有这样的东西。
class WorkingDaySerializer(serializers.ModelSerializer):
workdays = serializers.IntegerField(read_only=True)
class Meta:
model = WorkingDay
fields = '__all__'
read_only_fields = ['workdays']
在您看来,您可能会做这样的事情。
class WorkingDayAPI(APIView):
"""
{ "start":"2018-01-01",
"end":"2018-05-01"
}
GET work days between dates
"""
serializer_class = WorkingDaySerializer
def get(self, request, format=None):
business_days = WorkingDay.objects.all()
serializer = WorkingDaySerializer(business_days, many=True)
return Response(serializer.data)
def post(self, request, *args, **kwargs):
start = request.data.get('start')
end = request.data.get('end')
# bizdays = request.data.get('bizdays')
business_days = WorkingDay.objects.create(**request.data)
business_days.start = start
business_days.end = end
business_days.workdays = workdays
business_days.save()
serializer = WorkingDaySerializer(business_days)
return Response(serializer.data, status=status.HTTP_201_CREATED)