Skip to content
Advertisement

Add time in django Models.py

I tried subtracting two times in models.py but I got error. Here is my model That I have been working.

class Schedule(BaseModel):
    bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) 
    travel_date_time = models.DateTimeField()

and BusCompanyRoute have journey length.

class BusCompanyRoute(BaseModel):
    journey_length = models.TimeField(null=True)

Now I tried adding these times in using @property decorator in following way

@property
def journey_end_time(self):
    return self.travel_date_time.time()+self.bus_company_route.journey_length

but end up getting following error warning as: Class 'time' does not define '__add__', so the '+' operator cannot be used on its instances How can I solve it?

Advertisement

Answer

A DurationField is more appropriate for storing the duration of a journey not a TimeField, this will give you a timedelta that you can add or subtract from a datetime whereas a TimeField just gives a static time of day

class BusCompanyRoute(BaseModel):
    journey_length = models.DurationField(null=True)
Advertisement