1

this is related to a question I posed earlier.. ok, so I have a model with a custom save method that subtracts one date from another and returns "total_days":

class LeaveRequest(models.Model):
employee = models.ForeignKey(UserProfile)
supervisor = models.ForeignKey(UserProfile, related_name='+', blank=False, null=False)
submit_date = models.DateField(("Date"), default=datetime.date.today)
leave_type = models.CharField(max_length=64, choices=TYPE_CHOICES)
start_date = models.DateField(("Date"))
return_date = models.DateField(("Date"))
total_days = models.IntegerField()
notes = models.TextField(max_length=1000)

def __unicode__ (self):
    return u'%s %s' % (self.employee, self.submit_date)

def save(self, *args, **kwargs):
    self.total_days = (self.return_date - self.start_date).days
    super(LeaveRequest, self).save(*args, **kwargs)

    class Admin: 
            pass

    class Meta:
            ordering = ['-submit_date']

this works well except it doesn't factor in weekends. How would I tweak the logic (either in the model or in the view) to get "total_days" minus weekend days?

kjarsenal
  • 934
  • 1
  • 12
  • 35

1 Answers1

0

You can use the Python datetime library for this.

See this post for a python implementation.

from datetime import date, timedelta

...    

def save(self, *args, **kwargs):
    daygenerator = (self.start_date + timedelta(x+1) for x in xrange((
                    self.return_date - self.start_date).days))
    self.total_days = sum(1 for day in daygenerator if day.weekday() < 5)
    super(LeaveRequest, self).save(*args, **kwargs)
Community
  • 1
  • 1
Teisman
  • 1,318
  • 2
  • 13
  • 26
  • went to the post you referred; wrote a new save def based on that answer (pretty much same as yours, just worded differently), tested – works like a charm. I am grateful, sir. – kjarsenal Jan 21 '13 at 20:28