Skip to main content
 首页 » 编程设计

python之Django 查询 : Group by field and get the latest entry per group

2025年01月19日59mq0036

我在 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 不允许“分组”吗?

请您参考如下方法:

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

尝试一下:

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