获取过去三个月 Django 每个月的前 5 名用户
Get the Top 5 users in each month for the last three months Django
我有这个问题
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_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 = ...
window 函数在这里可能会派上用场
https://docs.djangoproject.com/en/3.2/ref/models/expressions/#window-functions
我有这个问题
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_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 = ...
window 函数在这里可能会派上用场 https://docs.djangoproject.com/en/3.2/ref/models/expressions/#window-functions