Home > database >  How to make calculation inside annotate?
How to make calculation inside annotate?

Time:01-11

This one when I run generates error

qs = User.objects.annotate(days=(datetime.now() - F("created_at")).days)
AttributeError: 'CombinedExpression' object has no attribute 'days'

How can I make that calculation as an annotation

When I run this code, it wroks fine

qs = User.objects.annotate(days=(datetime.now() - F("created_at")))

CodePudding user response:

This can be achieved with a combination of ExpressionWrapper, which tells django what the output field type should be, and ExtractDay which, well, extracts the day.

In this case, the output field is a timedelta object (i.e DurationField). ExtractDay is just a DB-level function which the django ORM provides.

from django.db.models import DateTimeField, DurationField, ExpressionWrapper, F
from django.db.models.functions import ExtractDay

qs = User.objects.annotate(
    days=ExtractDay(
        ExpressionWrapper(
            datetime.now() - F("created_at"), output_field=DurationField()))
    )

  • Related