我有對象報告和ReportSubscriber,我想統計報告的訂閱者數量。Django過濾器,分頁和標註分頁結果
一種解決方案是註釋。我有很多的報告,以便註釋所有的人都需要〜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']
)
但這仍然沒有奏效。我爲所有報告獲得了一個靜態數量的訂閱者。我錯過了什麼,也許有更好的方法來實現這個目標?謝謝