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