我有对象报告和报告订阅者,我想计算报告的订阅者数量。
一种解决方案是注释。我有很多报告,因此对所有报告进行注释大约需要 6 秒,所以我认为在分页后进行注释可能会更好:
filter_search = ReportFilter(request.GET, queryset=Report.objects.filter(
created_at__gt=start_date,
created_at__lte=end_date,
is_confirmed__exact=True,
).annotate(sub_count=Count("reportsubscriber")).order_by('-sub_count'))
paginator = Paginator(filter_search, 20)
result = paginator.page(1).object_list.annotate(
sub_count=Count("reportsubscriber"))
它起作用了,但是花费了相同的时间,当我检查查询时,它实际上仍然遍历了 report_subscriber 表中的所有行。所以我尝试使用 .extra()
filter_search = ReportFilter(request.GET, queryset=Report.objects.filter(
created_at__gt=start_date,
created_at__lte=end_date,
is_confirmed__exact=True,
))
paginator = Paginator(filter_search, 20)
paged_reports = paginator.page(1)
result = filter_search.qs.extra(
select={
'sub_count': 'SELECT COUNT(*) FROM reports LEFT OUTER JOIN report_subscribers \
ON (reports.id = report_subscribers.id) \
WHERE reports.id = report_subscribers.id \
AND report_subscribers.report_id IN %s \
' % "(%s)" % ",".join([str(r.id) for r in paged_reports.object_list])
},
order_by=['sub_count']
)
但这仍然没有奏效。我为所有报告获得了一个静态订阅者数量。我错过了什么,也许有更好的方法来实现这一点?谢谢