Django Query:按字段分组并获取每组的最新条目

时间:2017-10-23 21:00:58

标签: python django django-queryset

我在Django-1.11中有下表:

class Market(models.Model):
    slug = models.SlugField(...)
    active = models.DateTimeField(...)

如果slug是一个避免重复值的外键会很棒但事实并非如此,我正在处理第三方应用。

data = [
    {'id': 1, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>)'}, 
    {'id': 2, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>)'}, 
    {'id': 3, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>)'},
    {'id': 4, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>)'},
]

我正在寻找一个查询,它将返回带有slug test-1的最新条目和带有slug test-2的最新条目。

Using annotate我刚收到日期时间的结果:

Market.objects.values('slug').annotate(Max('active'))
Out[11]: <QuerySet [
{'active__max': datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'},
{'active__max': datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'},
{'active__max': datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'},
{'active__max': datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'}
]>

此结果似乎不符合the docs。我究竟做错了什么?是SlugField不允许&#34;分组&#34;?

1 个答案:

答案 0 :(得分:1)

看起来您需要在结果查询中通过default-ordering-or-order-by添加空order_by(),可以将额外字段添加到组中。

试一试:

Market.objects.values('slug').annotate(Max('active')).order_by()