django-relativedelta icon indicating copy to clipboard operation
django-relativedelta copied to clipboard

Unable to combine with Extract function

Open sevdog opened this issue 3 years ago • 1 comments

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.

sevdog avatar Oct 12 '22 10:10 sevdog

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',
  ),
)

sevdog avatar Oct 12 '22 13:10 sevdog