【问题标题】:Django Query: Group by field and get the latest entry per groupDjango Query:按字段分组并获取每个组的最新条目
【发布时间】:2017-10-23 21:00:57
【问题描述】:

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

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

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

    试试看:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2018-02-22
      • 1970-01-01
      • 2018-02-16
      相关资源
      最近更新 更多