Django Aggregate Between Timezone Aware Fields

Viewed 119

I want to find the average time between two dates - 'created_date' and 'modified_date'. Both are DateTimeField and values are timezone aware.

Color Model:

 name = models.CharField(max_length=150)
 is_published = models.BooleanField(default=False)
 created_date = models.DateTimeField(null=True, blank=True)
 modified_date = models.DateTimeField(null=True, blank=True)

To Save:

example.created_date = datetime.datetime.now(tz=timezone.utc)
example.save()

I ran the below query:

avg_change = Color.objects.filter(is_published=True, created_date__isnull=False, modified_date__isnull=False).aggregate(avg_score=Avg(F('modified_date') - F('created_date')))

I got the error below.

  if dt.tzinfo is not None:
AttributeError: 'decimal.Decimal' object has no attribute 'tzinfo'

I'm on Python3.6/Django2.2/mysql 5.7.

I'm not sure if I need to change the values to naive and then aggregate. What am I missing? Any viable route to approach this as I am not good with raw SQL.

1 Answers

I later did this:

from django.db.models import F, ExpressionWrapper
from django.db import models

avg_duration = ExpressionWrapper(F('modified_date') - F('created_date'), output_field=models.DurationField())
avg_change = Color.objects.filter(is_published=True, created_date__isnull=False, modified_date__isnull=False).aggregate(avg_score=Avg(avg_duration))

If you know of a more better option kindly share.

Related