Django在过滤器集中获得最新的3个结果



我正在尝试创建一个执行以下操作的查询:

  • 列表仅在过去4个月内结果 - 检查
  • 删除最佳时间为0的结果 - 检查
  • 列出独特的俱乐部和团队 - 检查
  • 从集合中获得最佳时光 - 检查
  • 将俱乐部和团队秩序井然-Check

我现在需要的唯一条件是:

  • 如果俱乐部或团队列出了3次以上(在获得最佳时间之前),请仅取3个最新结果。

-

place = Placing.objects 
.filter(event_date__gte=start_date) 
.filter(best_time__gt=0) 
.values_list('club_name','team_name') 
.annotate(Min('best_time')) 
.order_by('club_name','team_name')

您将不得不 LIMIT查询(通过python切片),这意味着您也必须分别为每个团队查询,因为我不认为LIMIT条款可以多次表示 - 在加号上,您将能够 aggregate(Min('best_time'))

如果您需要具有Placing对象的QuerySet,则可以与|运算符构建一个将结果构建。

另外,俱乐部和团队有什么区别?

编辑:也许这样的东西

from django.db.models import Min
besties = {}
for team in teams:
    besties[team] = Placing.objects 
    .filter(event_date__gte=start_date, best_time__gt=0).order_by(-event_date) 
    .filter(team_name=team)[:3].aggregate(Min('best_time'))['best_time__min']

最新更新