[Answered ]-How to use django annotate to compare current date with other date in models

1๐Ÿ‘

Just simply use F class to compare the time you wanted with one of the fields (start_working_date) of the model.

two tips:
1-for now time its better to use django timezone

2-you should use .date() method of now to be able to compare it with your start_working_date

from django.db.models import F
from django.utils import timezone    

employees = Employee.objects.annotate(
   duration=timezone.now().date() - F('start_working_date')
)

0๐Ÿ‘

Just try this __range

date_range = [from_date, to_date ]
emp = Employee.objects.filter(start_working_date__range=date_range)
๐Ÿ‘คAmar

0๐Ÿ‘

Use Value to pass and use a value in a query expression

from datetime import date
from django.db.models import F, Value

employees = Employee.objects.annotate(
    duration=Value(date.today()) - F('start_working_date')
)

Leave a comment