Django查询使用Group By获取最后一条记录

时间:2017-08-19 13:57:23

标签: django group-by sql-order-by django-queryset

我正在尝试根据ID获取所有最后的记录,按月排序。

这给了我最后一条记录,

qs = Cashflow.objects.filter ( acct_id = a.id ).order_by('-month')[:1]

这会将帐户分组,

qs = Cashflow.objects 
     .filter ( acct_id = a.id )
     .values ( 'acct_id' ) 
     .annotate ( count = Count ( 'acct_id' ) ) 
     .values ( 'acct_id', 'count' ) 
     .order_by ( ) 

如何将两个查询合并为一个?

按acct_id分组,按“月”排序并获得最后一条记录。

这甚至可能吗?感谢

编辑:

这是我想要做的sql版本。

    select * 
    from cashflow t
    inner join (
        select acct_id, max ( `month` ) as MaxDate
        from cashflow
          where acct_id  IN ( 1,2,3,... )
        group by acct_id
    ) tm on t.acct_id = tm.acct_id and t.month = tm.MaxDate
    order  by acct_id 

这可以在纯Django中完成,我应该只进行Raw查询吗?

欢呼声。

2 个答案:

答案 0 :(得分:-1)

相反.order_by('-month')[:1]最好使用.order_by('month').last().order_by('-month').first()(或earliest / latest作为日期。)

当然,在分组时,您可以使用order_by

last_record = Cashflow.objects \
    .values('acct_id') \
    .annotate(count=Count('id')) \
    .order_by('month') \
    .last() 

答案 1 :(得分:-2)

我在网上找到的最佳解决方案https://gist.github.com/ryanpitts/1304725

'''
given a Model with:

   category    = models.CharField(max_length=32, choices=CATEGORY_CHOICES)
   pubdate     = models.DateTimeField(default=datetime.now)
   <other fields>

Fetch the item from each category with the latest pubdate.

''' 

model_max_set = Model.objects.values('category').annotate(max_pubdate=Max('pubdate')).order_by()

q_statement = Q()
for pair in model_max_set:
    q_statement |= (Q(category__exact=pair['category']) & Q(pubdate=pair['max_pubdate']))

model_set = Model.objects.filter(q_statement)