Django查询:“datetime + delta”作为表达 [英] Django query : "datetime + delta" as an expression

查看:217
本文介绍了Django查询:“datetime + delta”作为表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我的问题有点如下:



假设我有下一个模型,这是一个简单的例子:

  class Period(models.Model):
name = CharField(... field specs here ...)
start_date = DateTimeField(。 ..字段规格在这里...)
持续时间= ...不知道我应该使用什么字段,但这必须持有三角洲...

我想检索其中(start_date + duration)<现在在django查询(我知道我可以,在python,测试像my_date_time + a_time_delta< datetime.now(),但不是这种情况...我需要它作为查询的一部分。)



如何获取?

解决方案

由于您的过滤器取决于两个属性相同的模型,您将需要使用 F()表达式持续时间部分,同时结合它有某种 timedelta 。目前,Django ORM不支持此功能。



尽管如此,您可以使用 extra()调用。这种方法的缺点是它不是与数据库无关的。这是PostgreSQL:

  Period.objects.extra(
where = [start_date + duration * INTERVAL'1 day'<%s],
params = [datetime.now()]

假设你的持续时间是几天。如果没有,请相应调整。


Well, my question is a bit as follows:

Suppose I have the next model, this is a simple case:

class Period(models.Model):
    name = CharField(... field specs here ...)
    start_date = DateTimeField(... field specs here ...)
    duration = ... don't know what field should i use but this has to hold a delta ...

I would like to retrieve objects where (start_date + duration) < now in a django query (i know i can, in python, test like my_date_time + a_time_delta < datetime.now(), but this is not the case ... i need it as part of the query).

How can i get it?

解决方案

As your filter depends of two attributes of the same model, you would need to use an F() expression for the duration part and at the same time combine it with some sort of timedelta. That's not supported in the Django ORM at the moment.

You can use an extra() call, though. The disadvantage of this approach is that it is not database-agnostic. This is for PostgreSQL:

Period.objects.extra(
    where=["start_date + duration * INTERVAL '1 day' < %s"],
    params=[datetime.now()]
)

assuming that your duration is in days. If not, adjust accordingly.

这篇关于Django查询:“datetime + delta”作为表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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