我正在检索所有记录,我想显示超过 5 分钟的记录的时间。
输出应该是这样的(在本例中,两条记录:1.8.9.1
和 2.7.3.1
超过 5 分钟):
ip ... status
---------------------
1.8.9.1 ... 3 hours
2.7.3.1 ... 7 minutes
1.1.1.1 ... up
1.1.1.2 ... up
1.1.1.3 ... up
1.1.1.4 ... up
1.1.1.5 ... up
这是我当前的代码:
Interfaces.objects.all()
.annotate(
age = (datetime.utcnow() - F('timestamp')), # 0:00:08.535704
age2 = Epoch(datetime.utcnow() - F('timestamp')), # 8.535704
# age3 = int(Epoch(datetime.utcnow() - F('timestamp'))/300),
current_time=Value(str(datetime.utcnow()),
output_field=null_char_field),
)
.order_by('age','ip')
age
和 age2
都有效,但问题是我想要按 age
排序超过 5 分钟的记录,并且其余的通过 ip
所以我尝试将 age
设置为 0
,如果它少于 5 分钟。
如果我直接在 postgresql 中执行,我会使用这个查询:
select ip, <other fields>,
case when extract('epoch' from now() - "timestamp") > 300
then extract('epoch' from now() - "timestamp")
else 0
end
有没有办法在 django 中做到这一点?
最佳答案
我想通了:
Interfaces.objects.all()
.annotate(
age=Case(
When(timestamp__lt=datetime.utcnow() - timedelta(minutes=5),
then=Cast(Epoch(datetime.utcnow() - F('timestamp')),
NullIntegerField)),
default=0,
output_field=NullIntegerField
),
)
.order_by('age','ip')
顺便说一下我的导入和相关设置:
from django.db.models import F, Func, Case, When, IntegerField
from django.db.models.functions import Coalesce, Cast
NullIntegerField = IntegerField(null=True)
class Epoch(Func):
function = 'EXTRACT'
template = "%(function)s('epoch' from %(expressions)s)"
这个网站最终是最有帮助的:https://micropyramid.com/blog/django-conditional-expression-in-queries/
关于django - 如果在 Django(使用 PostgreSQL 数据库)中超过 5 分钟(否则为 0),则以秒为单位获取记录的年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57063860/