Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unsupported operand type(s) for -: 'DateField' and 'DateField'

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)



Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading