Annotate queryset with comment count

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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,)
    )

More like this

  1. Allow filtering and ordering by counts of related query results by exogen 7 years ago
  2. Aggregation class "Count" with Case by marinho 3 years, 9 months ago
  3. Signal to notify new saved comments by arthurfurlan 4 years, 10 months ago
  4. Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view by jpic 5 years, 3 months ago
  5. Queryset Foreach by kcarnold 5 years ago

Comments

kioopi (on October 8, 2009):

That's pretty nifty. Will keep me from de-normalizing comment-counts for a while.

#

(Forgotten your password?)