从F()表达式创建的F()表达式和timedelta的总和 [英] Sum of F() expression and timedelta created from F() expression

查看:204
本文介绍了从F()表达式创建的F()表达式和timedelta的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的提案模型定义如下:

 类提案(models.Model):
scheduled_time = models .DateTimeField()
duration = models.IntegerField()#将分钟作为整数存储

#(为简洁起见,剪辑了额外的字段)
/ pre>

我想对每个投标对象进行注释,给它一个由schedule_time + timedelta表示持续时间计算的结束日期时间,例如 timedelta(分钟=持续时间)。但是,F()表达式似乎不作为 timedelta()的参数有效。

 >>>来自datetime import timedelta 
>>>>从django.db.models导入F
>>>从schedule.models导入提案
>>>
>>> proposal = Proposal.objects.all()
>>>注释= proposal.annotate(
... end = F('scheduled_time')+ timedelta(分钟= F('duration')))
追溯(最近的最后一次呼叫):
文件< console>,第1行,< module>
TypeError:timedelta分钟组件的不受支持的类型:F
>>>

使用 annotate()和F()表达式?



编辑:注释的目的是能够在计算结束时间过滤/排除

解决方案

F() - 表达式仅适用于django(as它们返回特定对象的实例)。你不能将它们传递给timedelta或者除了一些django查询方法之外的任何东西。



所以你最好向你添加新的模型:

 类提案(models.Model):
scheduled_time = models.DateTimeField()
duration = 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆