我有一张这样的桌子:
ID | Time Stamp
1 | 2012-07-28 18:57:48.160912+01
1 | 2012-07-28 20:57:43.063327+01
2 | 2012-07-28 21:17:16.016665+01
我想查看每个 id 的最新条目。
如果我这样做,我只会得到一个带有最新条目的对象:
open_deals = all_deals.latest('time_stamp'))
--> 2 | 2012-07-28 21:17:16.016665+01
但我想得到
--> 1 | 2012-07-28 20:57:43.063327+01
2 | 2012-07-28 21:17:16.016665+01
我需要以某种方式聚合或分组 ID。但是文档中没有此功能。
有小费吗?谢谢
更新:
我尝试了以下解决方案:
result_list = [deal.dealchangelog_set.latest('time_stamp') for deal in open_deals]
result_set = set()
for item in result_list:
result_set.add(item.pk)
return open_deals.filter(pk__in = result_set)
不幸的是,您可以看到该列表仍然包含三个对象而不是两个。:-(
这是我的模型(注意我没有使用 deal_id 作为 pk) pk 仍然是整数。就我而言,我需要获取最新的 deal_id,这不是唯一的。(为简单起见,我之前在这里将 uuid 显示为整数)
class Deal(models.Model):
deal_id = UUIDField()
status = models.ForeignKey(DealStatus, verbose_name=_(u"Deal Status"), null=True, blank=True)
contact = models.ForeignKey(Contact)
deal_type = models.ForeignKey(DealType)
class DealChangeLog(models.Model):
deal = models.ForeignKey(Deal)
time_stamp = CreationDateTimeField()
更新 2:
def get_open_deals(call):
all_deals = Deal.objects.filter(contact=call.contact)
closed_deals = all_deals.filter(status__in=[5, 6])
closed_deal_list = []
if closed_deals:
for item in closed_deals:
closed_deal_list.append(item.deal_id)
open_deals = all_deals.exclude(deal_id__in=closed_deal_list)
result_list = [deal.dealchangelog_set.latest('time_stamp') for deal in open_deals]
result_set = set()
for item in result_list:
result_set.add(item.pk)
return open_deals.filter(pk__in = result_set)