I am working on creating a contract model with Django and I came cross on how to get the time duration from the start_date to the end_date??
class Contract(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(max_length=10) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(auto_now_add=True) duration = models.IntegerField(end_date - start_date) # how get the duration by hours created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name
If you want to calculate a field in your model one good approach is to do that in an overridden save method.
Substracting one datetime from another results in a timedelta object. I am converting this here into seconds, assuming that is what you wanted.
class Contract(models.Model): ... duration = models.IntegerField() .... def save(self, *args, **kwargs): self.duration = (self.end_date - self.start_date).total_seconds() super().save(*args, **kwargs)