Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

python - Sum of F() expression and timedelta created from F() expression

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

class Proposal(models.Model):
    scheduled_time = models.DateTimeField()
    duration = IntegerField()
    end = models.DateTimeField(default=self.scheduled_time + timedelta(minutes=self.duration))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...