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

时间:2022-01-26 15:21:41

I am trying to create a query that does the following:

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

  • List results only from the last 4 months - Check
  • 仅列出过去4个月的结果 - 检查

  • Remove results where the best time is 0 - Check
  • 删除最佳时间为0的结果 - 检查

  • List unique clubs and teams - Check
  • 列出独特的俱乐部和球队 - 检查

  • Get the best times from the set - Check
  • 从集合中获得最佳时间 - 检查

  • Put the clubs and teams in order - Check
  • 把俱乐部和球队整理好 - 检查

The only condition i need now is:

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

  • If a club or team lists more than 3 times (before getting the best times), take the 3 most recent results only.
  • 如果俱乐部或团队列出超过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')

1 个解决方案

#1


You're going to have to LIMIT your query (through Python slicing), which means you are also going to have to query for each team separately as I don't think a LIMIT clause can be expressed multiple times - on the plus side, you will then be able to aggregate(Min('best_time'))!

您将不得不限制您的查询(通过Python切片),这意味着您还必须单独查询每个团队,因为我认为LIMIT子句不能多次表达 - 从正面看,然后你就可以聚合(Min('best_time'))!

If you need to have a QuerySet of Placing objects, you will be able to build one concatenating your results with the | operator.

如果您需要一个放置对象的QuerySet,您将能够构建一个将结果与|连接的结果运营商。

Also, what's the difference between Club and Team?

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

edit: maybe something like this

编辑:也许是这样的

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

#1


You're going to have to LIMIT your query (through Python slicing), which means you are also going to have to query for each team separately as I don't think a LIMIT clause can be expressed multiple times - on the plus side, you will then be able to aggregate(Min('best_time'))!

您将不得不限制您的查询(通过Python切片),这意味着您还必须单独查询每个团队,因为我认为LIMIT子句不能多次表达 - 从正面看,然后你就可以聚合(Min('best_time'))!

If you need to have a QuerySet of Placing objects, you will be able to build one concatenating your results with the | operator.

如果您需要一个放置对象的QuerySet,您将能够构建一个将结果与|连接的结果运营商。

Also, what's the difference between Club and Team?

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

edit: maybe something like this

编辑:也许是这样的

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