Django - 使用聚合查询集获取数据时很头疼
Django - Headache on getting data with aggregate queryset
一段时间以来,我在 Django 应用程序的模型之间进行连接和聚合时遇到了困难。
对于我的项目,我需要检索数据以便在 table 中显示它们。
在我的应用程序中,一种情况(在一段时间内)包括一个“数据系列”。
这些“dataserie”包含“instantdata”(某个日期的值)。
每个“dataserie”可以有不同的“source”(接收到的“instantdata”的来源)。
我想显示给定情况(通过 url /situation/int:primary_key 发送),情况来源列表(因此通过“ dataserie"), 以及源发送的最后一个“即时数据”日期,以确定每个源的“活动”日期。
例如,对于我的情况 1,我想要一个 table 这种类型的 :
Source
Last received date
Source Program1
02/02/2021 08:00:14
Source Program2
02/02/2021 07:30:14
我的模型文件和视图文件在这里:https://paste.ee/p/P8M4T
是否可以使用查询集?或者我应该在我的模板中使用 tempaltes 标签来处理这种事情吗?
这里有一些我试图理解和实现的资源:
https://docs.djangoproject.com/en/3.1/topics/db/aggregation/
https://hakibenita.com/how-to-use-grouping-sets-in-django
https://hakibenita.com/django-group-by-sql#how-to-sort-a-queryset-with-group-by
https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
你的 table 是一个源列表,所以我认为你应该尝试从这里制作你的查询集并像你尝试的那样添加注释:
sources_from_situation= Source.objects.filter(data_series__situation=situation)
sources_with_max_date = sources_from_situation.annotate(max_date=Max("data_series__instant_data__timestamp"))
for source in sources_with_max_date:
print((str(source), source.max_date))
一段时间以来,我在 Django 应用程序的模型之间进行连接和聚合时遇到了困难。
对于我的项目,我需要检索数据以便在 table 中显示它们。
在我的应用程序中,一种情况(在一段时间内)包括一个“数据系列”。
这些“dataserie”包含“instantdata”(某个日期的值)。
每个“dataserie”可以有不同的“source”(接收到的“instantdata”的来源)。
我想显示给定情况(通过 url /situation/int:primary_key 发送),情况来源列表(因此通过“ dataserie"), 以及源发送的最后一个“即时数据”日期,以确定每个源的“活动”日期。
例如,对于我的情况 1,我想要一个 table 这种类型的 :
Source | Last received date |
---|---|
Source Program1 | 02/02/2021 08:00:14 |
Source Program2 | 02/02/2021 07:30:14 |
我的模型文件和视图文件在这里:https://paste.ee/p/P8M4T
是否可以使用查询集?或者我应该在我的模板中使用 tempaltes 标签来处理这种事情吗?
这里有一些我试图理解和实现的资源:
https://docs.djangoproject.com/en/3.1/topics/db/aggregation/
https://hakibenita.com/how-to-use-grouping-sets-in-django
https://hakibenita.com/django-group-by-sql#how-to-sort-a-queryset-with-group-by
https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
你的 table 是一个源列表,所以我认为你应该尝试从这里制作你的查询集并像你尝试的那样添加注释:
sources_from_situation= Source.objects.filter(data_series__situation=situation)
sources_with_max_date = sources_from_situation.annotate(max_date=Max("data_series__instant_data__timestamp"))
for source in sources_with_max_date:
print((str(source), source.max_date))