How To Set A Timedelta In Between Two Model Datefields

i'm strugling some time already trying to set a timedelta in two fields of my model, then display de difference between then.

i've tried Stack and a lot of others tutorials and not quite shure if a should make a function on my models or my views, or a basic variable on the views i've tried all of them here is my code:


from django.db import models
from datetime import datetime
from datetime import timedelta

class To_do (models.Model):
    task = models.CharField(max_length=150)
    topic = models.CharField(max_length=150)
    how = models.TextField(max_length=600)
    start = models.DateField(blank=False)
    end = models.DateField(blank=False)

    def __str__(self):
        return self.task

class DetailView(DetailView):
    template_name = 'details.html'
    model = To_do

    def get_queryset(self):
        return To_do.objects.all()

    def get_delta(self):
        d1 = To_do.start
        d2 = To_do.end
        tdelta = d1-d2
        return tdelta

i want to display the difference between the star and end and after that, and after that setup an alarm if get less than three days. appreciate your help.



You can annotate your queryset to calculate the difference, like:

from django.db.models import DurationField, ExpressionWrapper, F

class DetailView(DetailView):
    template_name = 'details.html'
    model = To_do

    def get_queryset(self):
        return To_do.objects.annotate(
            delta=ExpressionWrapper(F('end') - F('start'), output_field=DurationField())

The object that arises from this queryset will have an extra field delta here that is a timedelta object that contains the difference between the end and the start.