如何使用@property方法制作涉及计算的POST方法

时间:2018-04-16 04:56:20

标签: django python-3.x django-rest-framework django-views python-requests

我正在使用REST FRAMEWORK并使用django 1.11构建API。我有Leave@property方法total_days我想制作POST方法,其中需要start_datereturn_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

1 个答案:

答案 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