python Django日期计算

56lgkhnf  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(111)

型号:

class JobCycle(models.Model):   

          dateReceived = models.DateField(blank=True, null=True)
          dueDate = models.DateField(blank=True, null=True)
          dateOut = models.DateField(blank=True, null=True)
          fee = models.IntegerField(blank=True, null=True)

         def __str__(self):
            return "Job Cycle" + str(self.id)

         def save(self, *args,**kwargs):
            if self.dateReceived and self.dueDate:
               if self.dateReceived > self.dueDate:
                raise ValidationError(
                    'Due date will never be greater than the received date')
            super(JobCycle, self).save(*args,**kwargs)

我想进行计算,到期日永远不会超过接收日期。我想在模型中执行此操作

ryevplcw

ryevplcw1#

您可以覆写模型的保存()方法:
def __str__(在同一级别)之前或之后添加:

def save(self, *args,**kwargs):
    if self.dueDate > self.dateReceived:
        raise ValidationError("dueDate must never be later than dateReceived!")
    super(JobCycle, self).save(*args,**kwargs)

或者,您可以更正dueDate,而不是引发错误:

self.dueDate = self.dateReceieve

取决于所需的逻辑。
验证错误来自:

from django.core.exceptions import ValidationError

相关问题