Django.fun

Make model function to stop counting

In a django app i have a model function that counting the progress of an event between date time fields. Is it possible to stop the progress after reaching 100. For example:

models.py

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

model function

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

Thank you

Answers: 2

Answered by yagus, Nov. 25, 2021, 12:54 p.m.

Simply use the Python min() function. That will return your progress calculation or 100 if the progress calculation is larger.

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
Answered by Henty, Nov. 25, 2021, 1 p.m.
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

This will return the progress once it the appointment is over. Maybe you will want to return True or something instead to assert the appointment is complete