[Answered ]-How to calculate numbers of days between two dates and subtract weekends DJANGO MODELS

1👍

UPDATE


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)


0👍

After Elvin’s answer I moved the hole logic to my view and set the logic inside form_valid function:

        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

Thank you all.

Leave a comment