Reputation: 2059
When I try to calculate a time difference between two fields using F expression it results in TypeError. I can't understand what's the problem, especially because there are other examples where F expressions were used to do the same (here: Timedelta between two fields)
model:
class TimeStamp(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Expression:
q = TimeStamp.objects.all().annotate(diff=F('created_at')-F('updated_at'))
print(q)
and error reports (not a full report):
File "lib/python3.5/site-packages/django/utils/dateparse.py", line 93, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
I use Django 1.8.8 if this matters.
Upvotes: 2
Views: 53
Reputation: 47354
Try to use ExpressionWrapper
with DurationField
:
from django.db.models import DurationField
q = TimeStamp.objects.all().annotate(diff=ExpressionWrapper(F('created_at')-F('updated_at'), output_field=DurationField()))
Upvotes: 2