【发布时间】:2026-02-09 13:20:04
【问题描述】:
我正在检索所有记录,我想显示那些超过 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 都可以,但问题是我希望超过 5 分钟的记录按 age 排序,其余按 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 中做到这一点?
【问题讨论】:
-
如果您仍然获得“所有记录”,一种选择是简单地使用
all()并在 Python 中进行任何您想要的排序和组织。
标签: django postgresql django-queryset