django-relativedelta
django-relativedelta copied to clipboard
Unable to combine with Extract function
When using this field is not possible to direcly use the Django ORM function Extract (and similars).
Since this function checks field type before passing to database:
ValueError: Extract input expression must be DateField, DateTimeField, TimeField, or DurationField.
This does not allow the developer to use with ease the postgres DB function EXTRACT.
A workaround for this is to use ExpressionWrapper:
from django.db.models import DurationField, ExpressionWrapper, F
from django.db.models.functions import Extract
MyModel.objects.annotate(
epoch=Extract(
ExpressionWrapper(F('myfield'), DurationField()),
'epoch',
),
)