【问题标题】:Get the Top 5 users in each month for the last three months Django获取过去三个月每个月的前 5 名用户 Django
【发布时间】:2021-05-27 09:01:45
【问题描述】:

我有这个问题

Post.objects.filter(issued_at__isnull=False, issued_at__gte=three_months_ago).annotate(
month=TruncMonth('issued_at'))[:5].values('month').annotate(num_of_posts=Sum('number_of_posts')).values(
'month', 'user__name', 'num_of_posts').order_by('-num_of_posts')[:15]

我现在只需要获取每个月的前 5 名用户(因此总共将返回 15 名用户)。如您所见,我尝试在注释之后对 5 进行切片,但是 AssertionError: Cannot reorder a query once a slice has been taken. 错误上升。另外,我尝试对 15 个用户进行切片,但没有成功,因为返回了错误的用户。

【问题讨论】:

  • * 请添加您的模型结构和关系。 * Top用户是什么意思?
  • @tarasinf by top 我的意思是创建帖子数量最多的用户。

标签: python django django-queryset django-orm


【解决方案1】:

我建议做三个查询:

top_month_1 = Post.objects.filter(
    issued_at__gte=months_ago_1,
).values(
    'user',
).annotate(
    posts_created=Count('user'),
).order_by('-posts_created')[:5]

top_month_2 = ...

top_month_3 = ... 

【讨论】:

  • 我不敢相信我之前没有想到这一点,我会接受这个答案,直到一个更方便的答案出现
【解决方案2】:

【讨论】:

  • 我检查了它,但不幸的是它没有工作,或者我没有弄清楚如何正确使用它们。
猜你喜欢
  • 1970-01-01
  • 2014-12-10
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多