2👍
✅
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()))
)
Source:stackexchange.com