Login

Get most-commented objects

Author:
ubernostrum
Posted:
March 14, 2007
Language:
Python
Version:
Pre .96
Tags:
managers comments popularity
Score:
10 (after 10 ratings)

This is a pretty straightforward bit of code for getting the most-commented objects of a particular model; just drop it into a custom manager for that model, and you should be good to go. Check the docstring for how to make it look at Comment instead of FreeComment.

 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
30
31
32
33
def most_commented(self, num=5, free=True):
    """
    Returns the ``num`` objects with the highest comment counts,
    in order.
    
    Pass ``free=False`` if you're using the registered comment
    model (Comment) instead of the anonymous comment model
    (FreeComment).
    
    """
    from django.db import connection
    from django.contrib.comments import models as comment_models
    from django.contrib.contenttypes.models import ContentType
    if free:
        comment_opts = comment_models.FreeComment._meta
    else:
        comment_opts = comment_models.Comment._meta
    ctype = ContentType.objects.get_for_model(self.model)
    query = """SELECT object_id, COUNT(*) AS score
    FROM %s
    WHERE content_type_id = %%s
    AND is_public = 1
    GROUP BY object_id
    ORDER BY score DESC""" % comment_opts.db_table
    
    cursor = connection.cursor()
    cursor.execute(query, [ctype.id])
    object_ids = [row[0] for row in cursor.fetchall()[:num]]
    
    # Use ``in_bulk`` here instead of an ``id__in`` filter, because ``id__in``
    # would clobber the ordering.
    object_dict = self.in_bulk(object_ids)
    return [object_dict[object_id] for object_id in object_ids]

More like this

  1. Model manager with row caching by jobs@flowgram.com 6 years, 9 months ago
  2. Allow filtering and ordering by counts of related query results by exogen 7 years, 11 months ago
  3. ActiveManager: filter objects depending on publication and/or expiration dates by haplo 6 years, 9 months ago
  4. Ordered items in the database - alternative by Leonidas 7 years, 10 months ago
  5. Cache Manager by jerzyk 7 years, 3 months ago

Comments

kerpunk (on March 24, 2010):

This wasn't working for me, so I changed each reference to object_id to object_pk, to reference the correct column in django_comments

#

Please login first before commenting.