在每个组的最近日期前获取第一个元素

时间:2021-03-26 14:31:54

I have following model in django

我在django有一个模型

Business ID
Business Name
Business Revenue
Date

Here is the sample data:

这是样本数据:

Business ID | Business Name | Business Revenue | Date
1             B1              1000               2012-10-13
2             B2              20000              2013-10-16
1             B1              2000               2013-04-13
2             B2              24000              2014-09-02

I want to fetch all businesses having latest date.

我想把所有有最新日期的公司都叫来。

Here is the output I want:

这是我想要的输出:

Business ID | Business Name | Business Revenue | Date
1             B1              2000               2013-04-13
2             B2              24000              2014-09-02

I have tried this:

我试过这个:

model.objects.filter(date__gte = date.today()).order_by('business_id', '-date')

This is giving me group of businesses having latest business in each group at the top of it. How do I omit the rest of rows? I need some assistance

这给了我一组企业的最新业务在每个集团的顶部。如何省略其余的行?我需要一些帮助

1 个解决方案

#1


1  

Try this:

试试这个:

from django.db.models import Q

group_dict = Model.objects.values('business_id').annotate(max_date=Max('date')).order_by()

params = Q()
for obj in group_dict:
    params |= (Q(business_id__exact=obj['business_id']) & Q(date=obj['max_date']))

qs = Model.objects.filter(params)

This link can help u.

这个链接可以帮助你。

If the values() clause precedes the annotate() clause, any annotations will be automatically added to the result set. However, if the values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column.

如果值()子句位于annotate()子句之前,则将自动将任何注释添加到结果集。

#1


1  

Try this:

试试这个:

from django.db.models import Q

group_dict = Model.objects.values('business_id').annotate(max_date=Max('date')).order_by()

params = Q()
for obj in group_dict:
    params |= (Q(business_id__exact=obj['business_id']) & Q(date=obj['max_date']))

qs = Model.objects.filter(params)

This link can help u.

这个链接可以帮助你。

If the values() clause precedes the annotate() clause, any annotations will be automatically added to the result set. However, if the values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column.

如果值()子句位于annotate()子句之前,则将自动将任何注释添加到结果集。