PageRenderTime 99ms CodeModel.GetById 92ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/comment_utils/managers.py

http://django-comment-utils.googlecode.com/
Python | 59 lines | 40 code | 7 blank | 12 comment | 3 complexity | bd845810e7309e3e4f5e9ecf09a9ec74 MD5 | raw file
 1"""
 2Custom manager which managers of objects which allow commenting can
 3inheit from.
 4
 5"""
 6
 7
 8from django.db import connection
 9from django.db import models
10from django.utils.datastructures import SortedDict
11from django.contrib.comments import models as comment_models
12from django.contrib.contenttypes.models import ContentType
13
14
15class CommentedObjectManager(models.Manager):
16    """
17    A custom manager class which provides useful methods for types of
18    objects which allow comments.
19    
20    Models which allow comments but don't need the overhead of their
21    own fully-defined custom manager should use an instance of this
22    manager as their default manager.
23    
24    Models which allow comments and which do have fully-defined custom
25    managers should have those managers subclass this one.
26    
27    """
28    def most_commented(self, num=5, free=True):
29        """
30        Returns the ``num`` objects of a given model with the highest
31        comment counts, in order.
32        
33        Pass ``free=False`` if you're using the registered comment
34        model (``Comment``) instead of the anonymous comment model
35        (``FreeComment``).
36        
37        """
38        qn = connection.ops.quote_name
39        
40        if free:
41            comment_opts = comment_models.FreeComment._meta
42        else:
43            comment_opts = comment_models.Comment._meta
44        ctype = ContentType.objects.get_for_model(self.model)
45        
46        subquery = """SELECT COUNT(*)
47        FROM %(comment_table)s
48        WHERE %(comment_table)s.%(content_type_id)s = %%s
49        AND %(comment_table)s.%(object_id)s = %(self_table)s.%(pk)s
50        AND %(comment_table)s.%(is_public)s = %%s
51        """ % { 'comment_table': qn(comment_opts.db_table),
52                'content_type_id': qn('content_type_id'),
53                'object_id': qn('object_id'),
54                'self_table': qn(self.model._meta.db_table),
55                'pk': qn(self.model._meta.pk.name),
56                'is_public': qn('is_public'),
57                }
58        
59        return self.extra(select=SortedDict({ 'comment_count': subquery }), select_params=(ctype.id, True,), order_by=['-comment_count'])[:num]