我有一个django模板,它显示上次在数据库中更新元素的时间,如下所示:
<small>updated {{ updated|timesince }} ago</small>
其中updated
是该元素上次更新的时间戳。
所以我写了这段代码试图让这种情况发生:
{% if is_updated%}
{% if updated|timesince == '0 minutes' %}
<small>updated just now </small>
{% else %}
<small>updated {{ updated|timesince }} ago</small>
{% endif %}
{% endif %}
这里is_updated
是一个像这样设置的上下文变量:
if element.updated != element.uploaded:
is_updated = True
然而,它总是让我在X分钟前更新&#39;即使该元素尚未更新。我能做错什么?
元素的模型:
title = models.CharField(max_length=120)
identifier = models.SlugField(blank=True, null=True)
category = models.CharField(max_length=120, default="uncategorized")
description_short = models.CharField(max_length=300, default="none")
description = models.TextField(default="none")
uploaded = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
time = models.IntegerField()
答案 0 :(得分:1)
即使一个实例只创建一次并且再也没有触及过,两个auto_add
和auto_add_now
DateTimeFields
可以保持略有不同的时间戳。如果你在shell中检查它,你会看到像:
>>> element.uploaded
datetime.datetime(2018, 1, 4, 14, 7, 37, 542192, tzinfo=<UTC>)
>>> element.updated
datetime.datetime(2018, 1, 4, 14, 7, 37, 542213, tzinfo=<UTC>)
你注意到微秒的差异。你应该用一点ε来检查他们的平等:
if (element.updated - element.uploaded).microseconds > 500:
is_updated = True
timesince
不支持一分钟内的时间增量。来自the docs:
分钟是使用的最小单位,并且对于将来相对于比较点的任何日期将返回“0分钟”。
您所能做的就是将额外信息提供给上下文:
# view
recent = (element.updated - element.uploaded).seconds < 60
# template
{% if recent %}
<small>updated just now </small>
{% else %}
<small>updated {{ updated|timesince }} ago</small>
{% endif %}