【问题标题】:Timestamp TruncHour aggregation in DjangoDjango中的时间戳TruncHour聚合
【发布时间】:2018-03-08 20:54:56
【问题描述】:

我有一个包含人数和时间戳的数据,我想以小时格式汇总显示。人数对象的模型如下所示:

class PeopleCount(models.Model):
    """
    A webapp model classs to store People Count Details.
    """
    timestamp = models.DateTimeField(auto_now=True)
    people_count_entry = models.IntegerField(blank=True, null=True)
    people_count_exit = models.IntegerField(blank=True, null=True)
    store = models.ForeignKey(Store, blank=True, null=True)
    profile = models.ForeignKey(Profile)
    camera = models.ForeignKey(Camera)
    recorded_time = models.DateTimeField(null=True, blank=True)

    def str(self):
        return "People Count {}".format(self.timestamp)

    class Meta:
        verbose_name = "People Count"
        verbose_name_plural = "People Count"
        ordering = ['-timestamp']

我正在使用以下查询按小时获取数据:

queryset = PeopleCount.objects.filter(
                    **json.loads(
                        self.request.query_params['filter'])['object_params']
                ).annotate(
                    time_series=TruncHour('recorded_time')).values(
                    'time_series').annotate(
                    people_count_entry=Sum('people_count_entry')).values(
                    'time_series',
                    'people_count_entry').annotate(
                    people_count_exit=Sum('people_count_exit')).values(
                    'time_series', 'people_count_entry',
                    'people_count_exit')

上述查询的问题在于它实际上并没有按小时聚合,而是为每个时间戳保留单独的值 我必须在客户端进行操作。 客户端的方法有效,但较大的查询集需要大量时间。 希望我的问题陈述清楚。 谢谢。

【问题讨论】:

    标签: django django-models orm django-orm


    【解决方案1】:

    阅读Aggregation - Interaction with default ordering or order_by()

    查询集的 order_by() 部分中提到的字段(或在模型的默认排序中使用的字段)在选择输出数据时使用,即使它们不是以其他方式使用的在 values() 调用中指定。这些额外的字段用于将“喜欢”的结果组合在一起......

    queryset = (
        PeopleCount.objects
        .filter(**json.loads(self.request.query_params['filter'])['object_params'])
        .order_by()    # THIS IS THE FIX - remove ordering by 'object_params'
        .annotate(time_series=TruncHour('recorded_time'))
        .values('time_series')  # output only this - to be grouped
        .annotate(
            people_count_entry=Sum('people_count_entry'),
            people_count_exit=Sum('people_count_exit'),
        )
        # no need to add or remove fields by .values()
        .order_by('time_series')  # order by truncated not by individual !!!
    )
    # print(str(queryset.query))  # SQL check is perfect for debugging
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 2023-03-11
      • 2016-09-24
      • 2021-10-04
      相关资源
      最近更新 更多