将日期时间与其他字段中的时间增量进行比较(F()对象) [英] Datetime comparison with a timedelta from an other field (F() objects)

查看:99
本文介绍了将日期时间与其他字段中的时间增量进行比较(F()对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为查询集过滤创建条件。

I'm trying to make a condition for a queryset filtering.

我模型的2个字段,一个字段代表时间增量(分钟数),一个字段代表日期时间( start_datetime ),以及 datetime.datetime .now()(又名 now )。

It implies 2 fields of my model, one field representing a timedelta (a number of minutes), one field representing a datetime (start_datetime), and datetime.datetime.now() (aka. now).

我想检查开始日期时间-现在< = time_delta

我已经看到了示例(从 doc ),我们可以比较两个日期(时间)和一个恒定的时间增量。

I've seen the example (from the doc) in which we're able to compare two date(time)s and a constant timedelta.

>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))

但是如果它是我输入的其他字段中包含的值怎么办?

But what if it's a value contained in an other field of my entry?

显然不允许我尝试实例化此时间增量的方法。

The way I try to instanciate this timedelta is obviously not permitted.

>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=F('n_timedelta')))

是否可以找到使用ORM功能实现此目标的解决方案?
我想尽可能避免使用一些原始SQL。

Could there be a solution to achieve this using the ORM features? I'd like to avoid using some raw SQL as much as possible.

推荐答案

我想我找到了一个解决方案。

I think I found a solution.

我在不同的转换和转换方面非常挣扎,所以我尝试了另一种方式:

I struggled too much with different conversions and casts, so I tried an other way:

我申请了 time_delta 属性上的过滤条件,并使用两个日期之间的差值从中提取自EPOCH时间以来的秒数,然后除以60得到分钟数:

I applied the filtering condition on the time_delta attribute, and used the difference between both dates from which I extracted the number of seconds since EPOCH time, then divided by 60 to get the number of minutes :

其中给出了类似的内容:

Which gave something like :

>>> from django.db.models import F
>>> from django.db.models.functions import Extract, Now
>>> Entry.objects.filter(
...     time_delta__gte=(Extract(F("start_datetime"), "epoch") - Extract(Now(), "epoch"))/60
... )

这篇关于将日期时间与其他字段中的时间增量进行比较(F()对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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