Home > Software design >  Computing difference between two datefields in Django Model
Computing difference between two datefields in Django Model

Time:11-18

I have two datefields fields in a Django model, start_date and end_date. I want to calculate and store the total number of days between the two, which will be used alongside a daily fee to return total cost.

models.py

class Booking(models.Model):
    """Stores the bookings, for example when it was made, the booking date, and the car ID."""
    # Unique ID for this booking.
    start_date = models.DateField(default=timezone.now)
    end_date = models.DateField(null=True)

Most answers recommend extracting the days function (using start_date.day) but that doesn't work. If a booking starts on November 30, and ends on December 2, the function will return 28 days because it subtracts the integers alone.

Using simple addition and subtraction:

duration = end_date - start_date 

returns an error:

TypeError: Unsupported Operand type(s) for -: 'DateField' and 'DateField'

I've tried using a function nested within the model, which subtracts each day from end_date until it reaches start_date:

    def get_total_days(self):
        """Computes total number of days car will be rented from with a basic While loop."""
        # Create separate instances of start and end day so as not to tamper with db values.
        start_day = self.start_date
        end_day = self.end_date
        days = 0
        while end_day > start_day:
            days  = 1
            end_day -= 1
        return days

But that raises the error:

Exception Value: unsupported operand type(s) for -=: 'datetime.date' and 'int'

Can you help with this?

CodePudding user response:

Add a method or property that subtracts the dates of an instance:

@property
def duration(self):
    return (self.end_date - self.start_date).days
  • Related