如何计算两个日期之间的天数并减去周末 DJANGO 模型

How to calculate numbers of days between two dates and subtract weekends DJANGO MODELS

希望你一切都好!

我有一个名为 Vacation 的模型,我正在努力处理一个字段:days_requested,这个字段是从 vacation_startvacation_end 开始的天数,它工作并给了我一个整数作为结果。我现在面临的问题是我需要减去周末(或者不计算)。

我有:

vacation_start = '2022-05-20'
vacation_end = '2022-05-24'
days_requested = 5

我想要的:

vacation_start = '2022-05-20'
vacation_end = '2022-05-24'
days_requested = 3

#21/05 and 22/05 are weekends

度假模特:

class Vacation(models.Model):
    department = models.ForeignKey(
        'departments.Department', on_delete=models.SET_NULL, null=True)
    responsible = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, related_name='responsible_vacation')
    status = models.CharField(
        max_length=20, choices=STATUS_CHOICES_VACATIONS, default='open')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, related_name='created_by_vacation')
    vacation_start = models.DateField(blank=False)
    vacation_end = models.DateField(blank=False)
    days_requested = property(
        lambda self: (self.vacation_end - self.vacation_start).days + 1
    )
    def __str__(self):
        return str(self.created_by.first_name + ' ' + self.created_by.last_name)

我试过:

    days_requested = property(
         lambda self: [(self.vacation_start + datetime.timedelta(days=i)).date()
                      for i in range(0, (self.vacation_end - self.vacation_start)) if (self.vacation_start + datetime.timedelta(days=i)).weekday() not in [5, 6].days()])

但我收到以下错误:

'datetime.timedelta' object cannot be interpreted as an integer

当我根据要求的天数执行操作时,我需要能够得到一个整数。

提前谢谢大家。

更新


class Model:
    days_requested = models.IntegerField(blank=True,null=True)
    
    
      def save(self, *args, **kwargs):
        excluded = (6, 7)
        days = 0
        start_date =self.vacation_start
        while start_date < self.vacation_end:
            if start_date.isoweekday() not in excluded: #if you want to get only weekdays
                days += 1
                start_date+= timedelta(days=1)
         
        self.days_requested=days

        super(YourModel, self).save(*args, **kwargs)


在 Elvin 的回答后,我将洞逻辑移到了我的视图中,并在 form_valid 函数中设置了逻辑:

        start = form.instance.vacation_start
        end = form.instance.vacation_end
        delta = end - start
        excluded = (6, 7)
        days = 0
        for i in range(delta.days + 1):
            day = start + datetime.timedelta(days=i)
            if day.isoweekday() not in excluded:
                days += 1
        form.instance.days_requested = days

谢谢大家