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]
|
Comments