My Proposal model is defined as follows:
class Proposal(models.Model):
scheduled_time = models.DateTimeField()
duration = models.IntegerField() # stores minutes as an integer
# (extra fields clipped for brevity's sake)
I want to annotate each proposal object, giving it an ‘end’ datetime calculated by scheduled_time + a timedelta representation of duration, e.g. timedelta(minutes=duration). However, F() expressions don’t seem to be valid as an argument to timedelta().
>>> from datetime import timedelta
>>> from django.db.models import F
>>> from schedule.models import Proposal
>>>
>>> proposals = Proposal.objects.all()
>>> annotated = proposals.annotate(
... end=F('scheduled_time')+timedelta(minutes=F('duration')))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: unsupported type for timedelta minutes component: F
>>>
Is this sort of thing possible using annotate() and F() expressions?
edit: The purpose of the annotation is to be able to filter/exclude on the computed end time.
F()-expressions works only with django (as they return instances of specific objects). You can’t pass them to timedelta or whatever except some of the django queryset methods.So you’d better add new field to you model: