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

Computing difference between two datefields in Django Model

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.

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

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?

>Solution :

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

@property
def duration(self):
    return (self.end_date - self.start_date).days
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