带时间戳的Django过滤器模型

时间:2018-04-18 16:57:01

标签: django filter model timestamp

我有以下型号:

class User(models.Model):
    id = models.CharField(max_length=10, primary_key=True)

class Data(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    timestamp = models.IntegerField(default=0)

鉴于单个用户,我想知道如何使用时间戳进行过滤。例如:

从现在到1小时之前,从user1获取数据。

我的当前时间戳为now = time.time(),我还有1小时前使用hour_ago = now-3600

我想获取具有这两个值之间的时间戳的数据。

2 个答案:

答案 0 :(得分:2)

使用range获取两个值之间的数据。

您可以在任何可以在SQL中使用BETWEEN的范围内使用范围 - 包括日期,数字甚至字符。

e.g。

Data.objects.filter(timestamp__range=(start, end))

来自docs:

import datetime start_date = datetime.date(2005, 1, 1) 
end_date = datetime.date(2005, 3, 31) 
Entry.objects.filter(pub_date__range=(start_date, end_date))  

答案 1 :(得分:1)

您可以使用__gtegreater than or equal to__lte引用less than or equal to,请尝试使用,

Data.objects.filter(timestamp__gte=hour_ago,timestamp__lte=now)


您可以在official doc

中找到类似的示例
相关问题