Django组连续几天(周五,周六,周日)

时间:2017-01-15 16:57:30

标签: django postgresql django-models django-aggregation django-database-functions

我每天都会发生一件事。这是模型

class Event(models.Model):
    date  = models.DateField()
    plays = models.IntegerField()
    viewers  = models.IntegerField()
    time = models.FloatField()

我试图连续几天(周五,周六,周日)汇总事件。

注意:周五和周六是同一周,周日是下一周。使用原始查询(postgres)我可以使用以下查询来聚合

SELECT DATE_TRUNC('week', "date")::date AS date,
       SUM(plays) AS total_plays,
       SUM(viewers) AS total_views,
       SUM(time) AS total_time
FROM  app_event
WHERE extract(isodow FROM date) IN (5,6,7)
GROUP BY date_trunc('week',"date")

然而在django中我找不到复制查询的方法

queryset = Event.objects.filter(date__week_day__in=[1, 6, 7])\
   .annotate('week'=TruncWeek('date')) \
   .values('week')\
   .annotate(total_views=Sum('views'), total_plays=Sum('plays'), total_time=Sum('time')) \
   .values('week', 'total_views', 'total_time', 'total_plays')

但是,此查询会在同一周内选择星期日,星期五和星期六。

0 个答案:

没有答案
相关问题