Home > Net >  How to use django annotate to compare current date with other date in models
How to use django annotate to compare current date with other date in models

Time:01-08

I want to get the days between the current time and another date. Here is the command what I used:

employees = Employee.objects.annotate(
        duration=ExpressionWrapper(datetime.now().date() - F('start_working_date'), output_field=DurationField())
        )

But the result I got( employee.duration) is 0.

for employee in employees:
    employee.duration

And here is my models:

class Employee(models.Model):
    name = models.CharField(max_length=30)
    start_working_date = models.DateField()

CodePudding user response:

Just try this __range

date_range = [from_date, to_date ]
emp = Employee.objects.filter(start_working_date__range=date_range)

CodePudding user response:

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')
)
  •  Tags:  
  • Related