1

这与我之前提出的一个问题有关.. 好的,所以我有一个带有自定义保存方法的模型,该方法从另一个日期中减去一个日期并返回“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']

这很好用,只是它不考虑周末。我将如何调整逻辑(在模型中或视图中)以获得“total_days”减去周末天数?

4

1 回答 1

0

您可以为此使用 Python 日期时间库。

有关 python 实现,请参阅这篇文章

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)
于 2013-01-21T20:02:43.250 回答