简体   繁体   English

Django平均在一个日期范围内

[英]Django averaging over a date range

I have a simple uptime monitoring app built in Django which checks if a site doesn't respond to a ping request. 我有一个在Django中构建的简单的正常运行时间监控应用程序,用于检查站点是否不响应ping请求。 It stores a timestamp of when it was pinged in the column "dt" and the millisecond response time in the column "ms". 它存储在“dt”列中固定的时间戳和“ms”列中的毫秒响应时间。 The site is pinged every minute and an entry is put into the database. 该站点每分钟都会被ping,并且一个条目被放入数据库中。

The Django model looks like this: Django模型看起来像这样:

class Uptime (models.Model):
    user = models.ForeignKey(User)
    dt = models.DateTimeField()
    ms = models.IntegerField()

I'd like to grab one day at a time from the dt column and take an average of the ms response time for that day. 我想从dt列一次抓取一天,并取平均当天的ms响应时间。 Even though there's 1440 entries per day I'd like to just grab the day (eg 4-19-2013) and get the average ms response time. 即使每天有1440个条目,我也想抓住那一天(例如4-19-2013)并获得平均ms响应时间。 The code I have been using below is undeniably wrong but I feel like I'm on the right track. 我在下面使用的代码无可否认是错误的,但我觉得我在正确的轨道上。 How could I get this to work? 我怎么能让这个工作?

       output_date = Uptime.objects.filter(user = request.user).values_list('dt', flat = True).filter(dt__range=(startTime, endTime)).order_by('dt').extra(select={'day': 'extract( day from dt )'}).values('day')
       output_ms = Uptime.objects.filter(user = request.user).filter(dt__range=(startTime, endTime)).extra(select={'day': 'date( dt )'}).values('day').aggregate(Avg('ms'))

Thanks! 谢谢!

You need to annotate to do the group by. 你需要注释来进行分组。 Django doesnt have anything in the orm for extracting only dates, so you need to add an "extra" parameter to the query, which specifies to only use the dates. Django在orm中没有任何东西只能提取日期,所以你需要在查询中添加一个“额外”参数,它指定只使用日期。 You then select only those values and annotate. 然后,您只选择这些值并注释。

Try the following: 请尝试以下方法:

Uptime.objects.filter(user=request.user).extra({'_date': 'Date(dt)'}).values('_date').annotate(avgMs=Avg('ms'))

This should give you a list like follows: 这应该给你一个如下列表:

[{'_date': datetime.date(2012, 7, 5), 'avgMs': 300},{'_date': datetime.date(2012, 7, 6), 'avgMs': 350}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM