【问题标题】:Make model function to stop counting使模型功能停止计数
【发布时间】:2022-01-03 14:20:09
【问题描述】:

在 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

谢谢

【问题讨论】:

    标签: django function datetime model


    【解决方案1】:
    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
    

    约会结束后,这将返回进度。也许你会想要返回 True 或其他东西来断言约会已经完成

    【讨论】:

      【解决方案2】:

      只需使用 Python min() 函数。如果进度计算较大,这将返回您的进度计算或 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
      

      【讨论】:

        猜你喜欢
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 2016-04-09
        • 2012-08-10
        • 1970-01-01
        相关资源
        最近更新 更多