這裏是一個片段,它可以幫助你:
http://djangosnippets.org/snippets/1101/
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
from django.db import connection
qn = connection.ops.quote_name
def qf(table, field): # quote table and field
return '%s.%s' % (qn(table), qn(field))
def comments_extra_count(queryset):
commented_model = queryset.model
contenttype = ContentType.objects.get_for_model(commented_model)
commented_table = commented_model._meta.db_table
comment_table = Comment._meta.db_table
sql = '''SELECT COUNT(*) FROM %s
WHERE %s=%%s AND %s=%s
''' % (
qn(comment_table),
qf(comment_table, 'content_type_id'),
qf(comment_table, 'object_pk'),
qf(commented_table, 'id')
)
return queryset.extra(
select={'comment_count': sql },
select_params=(contenttype.pk,)
)
您可以實現這一切在線,沒有定義這些方法。最終結果是帶有額外屬性comment_count的帶註釋的查詢集。排序:
qs_sorted_by_comment_count = comments_extra_count(some_qs).order_by('comment_count')
雖然我還不知道確切的答案,我認爲這將關係到聚集:http://docs.djangoproject.com/en/dev/topics/db/aggregation/#爲查詢集中的每個項目生成聚合 – Ponkadoodle 2011-05-11 01:03:03
無視此問題,DTing顯示聚合在GenericForeignKeys上不起作用。 – Ponkadoodle 2011-05-11 01:20:27
對我來說很奇怪,在django中實現按評論量排序是非常困難的。 – krzyhub 2011-05-11 13:03:32