PageRenderTime 71ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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