Django:如何进行聚合(GroupBy ID)&最新时间戳?

时间:2012-07-28 20:46:28

标签: django

我有一张这样的表:

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)

enter image description here

不幸的是,你可以看到列表仍然包含三个对象而不是两个。 : - (

这是我的模型(注意我没有使用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)

1 个答案:

答案 0 :(得分:0)

我不知道情境,但我可能会打破这样的模型:

class Deal(models.Model):
    title = models.CharField()
    # maybe signal changes etcetera... 

class DealChangeLog(models.Model):
    deal = models.ForeignKey(Deal)
    date = models.DateTimeField(auto_now=True, auto_now_add=True)

然后你可以通过列表理解来实现你的结果:

results = [deal.dealchangelog_set.latest('date') for deal in Deal.objects.all()]

要将结果作为查询集获取,您可以执行以下操作:

Deal.objects.filter(id__in=[result.deal.id for result in results])

但是,如果您可以将结果作为列表使用,我没有看到额外查询的重点