首页 > 解决方案 > 在 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'))

它确实按位置和类型对事件进行分组,但不返回attendancefield,这是所需的行为。

我尝试的另一种方法是使用 distinct 即:

event.objects.distinct('location', 'type').annotate(latest_date=Max('date'))

但我得到一个错误

NotImplementedError: annotate() + distinct(fields) is not implemented.

我找到了一些依赖于 Django 的数据库特定功能的答案,但我想找到一个与底层关系数据库无关的解决方案。

标签: djangodjango-querysetdjango-database

解决方案


好吧,我认为这个可能真的对你有用。它基于一个假设,我认为这是正确的。

当您创建模型对象时,它们都应该是唯一的。似乎极不可能有两个events 在同一个datelocation同一个type。因此,有了这个假设,让我们开始吧:(作为格式说明,类Names倾向于以大写字母开头以区分classesandvariablesinstances。)

# 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),但这应该会让您走上正确的道路。


推荐阅读