使模型功能停止计数

Make model function to stop counting

在 Django 应用程序中,我有一个模型函数,用于计算日期时间字段之间事件的进度。是否可以在达到100后停止进度。例如:

models.py

start_appointment = models.DateTimeField(default=timezone.now, blank=True)
end_appointment = models.DateTimeField(default=timezone.now, blank=True)

模型函数

def get_progress(self):
  if (self.status) == 'New' or (self.status) == 'Finished':
    now = timezone.now()
    progress = ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100
      if progress > 100.0:
         ...
      return progress

谢谢

只需使用Python min()函数即可。这将 return 您的进度计算或 100,如果进度计算更大。

def get_progress(self):
  if (self.status) == 'New' or (self.status) == 'Finished':
    now = timezone.now()
    progress = min(((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100, 100)
      return progress
def get_progress(self):
  return ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100

def other_process():
  while self.get_progress() < 100:
    Do stuff here...
  return progress

这将 return 约会结束后的进度。也许您会想要 return True 或其他东西来断言约会已完成