我正在使用REST FRAMEWORK
并使用django 1.11
构建API。我有Leave
类@property
方法total_days
我想制作POST
方法,其中需要start_date
和return_date
给出total_days
的结果。我如何在views.py中执行此操作?
以下是Leave
类:
class Leave(models.Model):
LEAVE_STATUS = (
('A', 'Approved'),
('R', 'Rejected'),
('P', 'Pending'),
)
leave_id = models.AutoField(primary_key=True)
applicant = models.ForeignKey(
User, related_name='applicant', on_delete=models.CASCADE)
approver = models.ForeignKey(
User, related_name='approver', on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
responded_on = models.DateTimeField(auto_now=True, null=True)
leave_type = models.ForeignKey(LeaveType)
number_of_days = models.IntegerField()
start_date = models.DateField()
return_date = models.DateField()
leave_status = models.CharField(
max_length=1, choices=LEAVE_STATUS, default='R')
additional_message = models.TextField(max_length=200)
leave_subject = models.CharField(max_length=40)
leave_reason = models.TextField(max_length=200)
total_days = models.IntegerField()
# approved_by
# leave count
@property
def total_days(self):
oneday = datetime.timedelta(days=1)
dt = self.start_date
total_days = 0
while(dt <= self.return_date):
if not dt.isoweekday() in (6, 7):
total_days += 1
dt += oneday
return totaldays
def __str__(self):
return self.leave_status
答案 0 :(得分:2)
试试这个,
from rest_framework.views import APIView
class MyAPI(APIView):
def total_days(self,start_date,return_date):
oneday = datetime.timedelta(days=1)
dt = start_date
total_days = 0
while (dt <= return_date):
if not dt.isoweekday() in (6, 7):
total_days += 1
dt += oneday
return total_days
def post(self,request,*args,**kwargs):
start_date = request.data.get('start_date')
return_date = request.data.get('return_date')
total_days = self.total_days(start_date,return_date)
# do some other stuff if you want
return some response