1

我有一张这样的桌子:

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)
4

1 回答 1

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])

但是,如果您可以将结果作为列表处理,我认为额外查询没有多大意义

于 2012-07-28T21:51:50.323 回答