Get First element by the recent date of each group

半城伤御伤魂 提交于 2020-05-12 06:50:34

问题


I have following model in 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:


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.




回答2:


You can use order_by and distinct() methods

Model.objects.all().order_by('business_id', '-date').distinct('business_id')


来源:https://stackoverflow.com/questions/40241872/get-first-element-by-the-recent-date-of-each-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!