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

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

问题描述

我的提案模型定义如下:

class Proposal(models.Model):schedule_time = models.DateTimeField()duration = models.IntegerField() # 将分钟存储为整数#(为简洁起见,剪掉了额外的字段)

我想注释每个提案对象,给它一个由 schedule_time 计算的结束"日期时间 + 持续时间的 timedelta 表示,例如timedelta(minutes=duration).但是,F() 表达式似乎不能作为 timedelta() 的参数.

<预><代码>>>>从日期时间导入时间增量>>>从 django.db.models 导入 F>>>from schedule.models import Proposal>>>>>>建议 = Proposal.objects.all()>>>注释 = 提案.annotate(... end=F('scheduled_time')+timedelta(minutes=F('duration')))回溯(最近一次调用最后一次):文件<console>",第 1 行,在 <module> 中类型错误:timedelta 分钟组件不支持的类型:F>>>

使用 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屋!

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