0

I have a Django model where I'd like to calculate a duration field based on the inputted data from two DateTime fields and store the difference between them in hours: minutes (I'm not even sure the duration field is the right choice here.

This is what I got so far.

class CarEventsData(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="events_of_cow")
    out = models.DateTimeField(null=True, help_text="When the cow went OUT TO Pasture.")
    _in = models.DateTimeField(null=True, help_text="When the cow got back IN FROM Pasture.")
    duration = models.DurationField()

    def save(self, *args, **kwargs):
        """
        Should set duration field to total time between out and in data.
        """
        self.duration = self.out - self._in
        super(CarEventsData, self).save(*args, **kwargs)

2 Answers2

0

Your code looks correct. If you want to save duration for some specific purpose then it's okay, you can do this way. There is a better way in which you don't have to save duration and derive the data at runtime.

class CarEventsData(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="events_of_cow")
    out = models.DateTimeField(null=True, help_text="When the cow went OUT TO Pasture.")
    _in = models.DateTimeField(null=True, help_text="When the cow got back IN FROM Pasture.")


    def duration(self):
        return self.out - self._in
Kaushal Kumar
  • 1,237
  • 1
  • 12
  • 21
0

You can add a helper function

helper.py
def get_overtime_application_hours(start_time, end_time) -> int:
    difference = end_time - start_time
    hours = difference.seconds/3600
    return hours 

import in your model

from .healper import get_overtime_application_hours

then

def duration(self):
    hours = get_overtime_application_hours(self.out, 
                self._in)
    return round(hours) 
Al Imran Hossain
  • 119
  • 1
  • 2
  • 12