how I get the difference between two dates in term of days?

I want to get the difference between two dates in term of days

       query = Sale.sales.all_sales(self.owner_id).filter(status='UNPAID', sales_date__gte= Dash.start_date , sales_date__lte= Dash.end_date).annotate(
            days_overdue= - F('due_date') ,
                When(days_overdue__lte = 30, then=Value('0-30')),
                When(days_overdue__lte = 60, then=Value('31-60')),
                When(days_overdue__lte = 90, then=Value('61-90')),
                When(days_overdue__gt = 90, then=Value('over 90 days')),
                output_field= CharField(max_length=50)

Django uses the PostgreSQL Interval data type for Python timedelta values.

To convert that to an integer days, you need to use the ExtractDay function

That portion of the query will look something like:

days_overdue= ExtractDay( - F('due_date'))

1 Like