2016-04-17 68 views
0

在Django應用程序中,我有一個名爲Comment的數據模型的查詢集。這包含用戶留下的文本註釋。在Django查詢集中計算出現頻率佔總數的百分比

想象一下'n'個用戶發表了評論。計算哪些用戶留下評論的百分比最快的方法是什麼?

現在,我想這將是:

Comment.objects.filter(commenter=<username>).count()/Comment.objects.count() 

你有什麼建議?我的目標是標記評論過多的人,以便屏蔽他們的帳戶以查找可能的垃圾郵件。我會大量運行這個查詢,因此關注性能。

回答

1

您應該避免爲數據庫中的每個用戶進行一次查詢。相反,你可以只用類似的查詢註釋爲每個用戶號碼(或甚至頂部n評議人):

from django.db.models import Count 

total_comments = Comment.objects.count() 
# Fetch top 10 commenters, annotated with number of comments, ordered by highest first 
User.objects.annotate(num_comments=Count('comment')).order_by('-num_comments')[:10] 
for user in users: 
    percentage = user.num_comments/total_comments 

這個例子假設你有一個User模型,您Comment有一個外鍵。

如果您要比較相關的評論數量,則評論總數的百分比實際上並不重要。