开发者

Django + ordering by comment amount

Does someone know what is solution for taking instances of commented model ordered by amount of comments?

I look at comments model class and it using:

    content_type   = models.ForeignKey(ContentType,
            verbose_name=开发者_如何学Go_('content type'),
            related_name="content_type_set_for_%(class)s")
    object_pk      = models.TextField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")


Here is a snippet that might help you out:

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,)
    )

You can implement this all inline, with out defining these methods. The end result is an annotated queryset with an extra attribute comment_count. To sort:

qs_sorted_by_comment_count = comments_extra_count(some_qs).order_by('comment_count')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜