从 F() 表达式创建的 F() 表达式和 timedelta 的总和 [英] Sum of F() expression and timedelta created from F() expression
问题描述
我的提案模型定义如下:
class Proposal(models.Model):schedule_time = models.DateTimeField()duration = models.IntegerField() # 将分钟存储为整数#(为简洁起见,剪掉了额外的字段)
我想注释每个提案对象,给它一个由 schedule_time 计算的结束"日期时间 + 持续时间的 timedelta 表示,例如timedelta(minutes=duration)
.但是,F() 表达式似乎不能作为 timedelta()
的参数.
使用 annotate()
和 F() 表达式可以实现这种事情吗?
注释的目的是能够过滤/排除计算的结束时间.
F()
-expressions 仅适用于 django(因为它们返回特定对象的实例).除了一些 django 查询集方法之外,你不能将它们传递给 timedelta 或其他任何东西.
所以你最好为你的模型添加新的字段:
class Proposal(models.Model):schedule_time = models.DateTimeField()持续时间 = IntegerField()end = models.DateTimeField(default=self.scheduled_time + timedelta(minutes=self.duration))
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:
class Proposal(models.Model):
scheduled_time = models.DateTimeField()
duration = IntegerField()
end = models.DateTimeField(default=self.scheduled_time + timedelta(minutes=self.duration))
这篇关于从 F() 表达式创建的 F() 表达式和 timedelta 的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!