这里是一个片段,它可以帮助你:
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