Login

Get most-commented objects

Author:
ubernostrum
Posted:
March 14, 2007
Language:
Python
Version:
Pre .96
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 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.