django - 在 Django 中聚合分组字段时返回对象
问题描述
假设以下示例模型:
# models.py
class event(models.Model):
location = models.CharField(max_length=10)
type = models.CharField(max_length=10)
date = models.DateTimeField()
attendance = models.IntegerField()
我想使用 Django ORM 获取每个活动地点和类型组合的最新日期的出席人数。根据Django Aggregation 文档,我们可以使用values
前面的annotation
.
...原始结果根据 values() 子句中指定的字段的唯一组合进行分组。然后为每个唯一组提供注释;注释是在组的所有成员上计算的。
因此,使用示例模型,我们可以编写:
event.objects.values('location', 'type').annotate(latest_date=Max('date'))
它确实按位置和类型对事件进行分组,但不返回attendance
field,这是所需的行为。
我尝试的另一种方法是使用 distinct 即:
event.objects.distinct('location', 'type').annotate(latest_date=Max('date'))
但我得到一个错误
NotImplementedError: annotate() + distinct(fields) is not implemented.
我找到了一些依赖于 Django 的数据库特定功能的答案,但我想找到一个与底层关系数据库无关的解决方案。
解决方案
好吧,我认为这个可能真的对你有用。它基于一个假设,我认为这是正确的。
当您创建模型对象时,它们都应该是唯一的。似乎极不可能有两个event
s 在同一个date
,location
同一个type
。因此,有了这个假设,让我们开始吧:(作为格式说明,类Names
倾向于以大写字母开头以区分classes
andvariables
或instances
。)
# First you get your desired events with your criteria.
results = Event.objects.values('location', 'type').annotate(latest_date=Max('date'))
# Make an empty 'list' to store the values you want.
results_list = []
# Then iterate through your 'results' looking up objects
# you want and populating the list.
for r in results:
result = Event.objects.get(location=r['location'], type=r['type'], date=r['latest_date'])
results_list.append(result)
# Now you have a list of objects that you can do whatever you want with.
您可能需要查找 的确切输出Max(Date)
,但这应该会让您走上正确的道路。
推荐阅读
- firebase - Firebase 不显示已连接的用户
- javascript - 未捕获的 ReferenceError:未定义 LoadFile 错误
- java - 两个视图,一个动画,但有一个问题
- javascript - Material UI Autocomplete Chip 多线
- node.js - 为什么 nodejs 调试在 VS-code 中不起作用?
- regex - laravel中文本字段错误的最大值验证
- c++ - 使用派生类创建基类对象
- node.js - 猫鼬查找特定文件的 x 文档
- python - 如何删除行索引的第二列?
- node.js - 在 Heroku 上部署应用程序(Nodejs + sqlite3)时出错