简体   繁体   English

Django按ID分组,然后选择最大时间戳

[英]Django group by id then select max timestamp

It might be a redundant question, but I have tried previous answers from other related topics and still can't figure it out. 这可能是一个多余的问题,但是我已经尝试了其他相关主题的先前答案,但仍然无法解决。

I have a table Board_status looks like this (multiple status and timestamp for each board): 我有一个表Board_status看起来像这样(每个板的多个状态和时间戳):

time      | board_id | status
-------------------------------
2012-4-5  |        1 | good

2013-6-6  |        1 | not good

2013-6-7  |        1 | alright

2012-6-8  |        2 | good

2012-6-4  |        3 | good

2012-6-10 |        2 | good

Now I want to select all records from Board_status table, group all of them by board_id for distinct board_id, then select the latest status on each board. 现在,我想从Board_status表中选择所有记录,将它们全部按board_id分组以区分不同的board_id,然后在每个board上选择最新状态。 Basically end up with table like this (only latest status and timestamp for each board): 基本上以这样的表结束(每个板只有最新状态和时间戳):

time      | board_id | status
------------------------------
2013-6-7  |        1 | alright

2012-6-4  |        3 | good

2012-6-10 |        2 | good

I have tried: 我努力了:

b = Board_status.objects.values('board_id').annotate(max=Max('time')).values_list('board_id','max','status')

but doesn't seem like it is working. 但似乎不起作用。 Still give me more than 1 record per board_id. 仍然给我每个board_id多于1条记录。

Which command should I use in Django to do this? 我应该在Django中使用哪个命令来执行此操作?

An update, this is the solution I use. 更新,这是我使用的解决方案。 Not the best, but it works for now: 并不是最好的,但目前可以使用:

b=[]
a = Board_status.objects.values('board_id').distinct()
for i in range(a.count()):
 b.append(Board_status.objects.filter(board_id=a[i]['board_id']).latest('time'))

So I got all board_id, store into list a. 所以我得到了所有的board_id,存储到列表a中。 Then for each board_id, do another query to get the latest time. 然后,对于每个board_id,执行另一个查询以获取最新时间。 Any better answer is still welcomed. 仍然欢迎任何更好的答案。

How will it work? 如何运作? You neither have filter nor distinct to filter out the duplicates. 您既没有过滤器也没有独特的过滤器来过滤出重复项。 I am not sure if this can be easily done in a single django query. 我不确定这是否可以在单个django查询中轻松完成。 You should read more on: 您应该阅读以下内容:

  1. https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct
  2. https://docs.djangoproject.com/en/1.4/topics/db/aggregation/ https://docs.djangoproject.com/en/1.4/topics/db/aggregation/

If you can't do it in 1 raw sql query, you can't do it with an OR mapper either as it's built on top of mysql (in your case). 如果您无法在1个原始sql查询中执行此操作,则也无法使用OR映射器进行操作,因为它是基于mysql构建的(对于您而言)。 Can you tell me how you would do this via raw SQL? 您能告诉我如何通过原始SQL进行此操作吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM