Queryset - Calculate date delta with today

Hi everyone,

I have to do a Queryset where i calculate the delta between a DateField() and the date of today. So far, i’ve managed to calculate this delta, with two DateField() of the same model.But when i want to calculate it with the date of today(i tried date.today(), datetime.now().date() and both of them, gave me 0 as a result).

Here is my model

    class Marche(models.Model):

    	titre = models.CharField(max_length=200)

    	date_entree = models.DateField(auto_now_add=True)
    	date_1 = models.DateField(null=True, blank=True)
    	date_2 = models.DateField(null=True, blank=True)

    	def __str__(self):
    		return self.titre

Here is the queryset and the output i get when i Calculate the difference between two dates ,that are in my model.(It’s to show you what works). The dates in this exemple are not accurate, it’s just for the test.

from django.db.models import F, ExpressionWrapper, fields
from task3.models import Marche
from django.utils.timezone import timedelta
import datetime

duree = ExpressionWrapper(F('date_2') - F('date_1') , output_field=fields.DurationField())
marche_duration = Marche.objects.annotate(duration=duree)

# Output
<QuerySet [
{'date_1': datetime.date(2021, 4, 22),
 'date_livraison': datetime.date(2021, 4, 9),
 'duration': datetime.timedelta(13)}, 

{'date_1': datetime.date(2021, 4, 22),
 'date_livraison': datetime.date(2021, 4, 6),
 'duration': datetime.timedelta(16)}]>

The goal is to be able to filter entries who have a delta superior to a certain integer.
The issue i’m facing is that when i change date_2 in the ExpressionWrapper, the delta is always equal to 0.

So i hope you can explain to me how to do the same calculation, bust instead of date_2. use the date of today. If you have any questions , i’m okay for it

Thanks in advance

Keep in mind that queries are executed by the database, not by Django - you can’t pass a Django function to the database for it to be executed there, you need to pass the output of that function.

Something like this would work:
.annotate(duration=Cast(now, DateField()) - F(‘date_1’), …)

(See the yellow warning box in the coalesce function docs for the example I used to draw this from.)