Hi Guys,
I’m currently working on a Django project where I need to calculate the number of days between two dates in a model. However, I’m running into an issue where the calculated day difference returns an extremely large and incorrect value (e.g., 26179200000000
days).
I have a model with a DateTimeField
:
class MyModel(models.Model):
date_received = models.DateTimeField(null=True, blank=True)
I want to calculate the difference in days between date_received
and the current date using Django ORM. Here’s the code snippet I’m using:
from django.db.models import F, ExpressionWrapper, IntegerField, Case, When
from django.db.models.functions import TruncDate, Now
days_in_storage = MyModel.objects.annotate(
days_diff=ExpressionWrapper(
TruncDate(Now()) - TruncDate(F('date_received')),
output_field=IntegerField()
)
)
Instead of getting a reasonable number of days (e.g., 1, 2, 100 days), I’m getting an enormous value like 26179200000000
days.
Has anyone encountered this issue before? Is there something I’m missing in the ORM query that could be causing this problem? How can I correctly calculate the day difference between two dates in Django ORM?
When I try this, I get this error.
Extract requires native DurationField database support.
days_in_storage = (ExtractDay(ExpressionWrapper(Now() - F('date_received'), output_field=DurationField())))