managers.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import unicode_literals
  2. from django_comments.managers import CommentManager as DjangoCM
  3. from mezzanine.conf import settings
  4. from mezzanine.core.managers import CurrentSiteManager
  5. class CommentManager(CurrentSiteManager, DjangoCM):
  6. """
  7. Provides filter for restricting comments that are not approved
  8. if ``COMMENTS_UNAPPROVED_VISIBLE`` is set to ``False``.
  9. """
  10. def visible(self):
  11. """
  12. Return the comments that are visible based on the
  13. ``COMMENTS_XXX_VISIBLE`` settings. When these settings
  14. are set to ``True``, the relevant comments are returned
  15. that shouldn't be shown, and are given placeholders in
  16. the template ``generic/includes/comment.html``.
  17. """
  18. visible = self.all()
  19. if not settings.COMMENTS_UNAPPROVED_VISIBLE:
  20. visible = visible.filter(is_public=True)
  21. if not settings.COMMENTS_REMOVED_VISIBLE:
  22. visible = visible.filter(is_removed=False)
  23. return visible
  24. def count_queryset(self):
  25. """
  26. Called from ``CommentsField.related_items_changed`` to store
  27. the comment count against an item each time a comment is saved.
  28. """
  29. return self.visible().count()
  30. class KeywordManager(CurrentSiteManager):
  31. def get_by_natural_key(self, value):
  32. """
  33. Provides natural key method.
  34. """
  35. return self.get(value=value)
  36. def get_or_create_iexact(self, **kwargs):
  37. """
  38. Case insensitive title version of ``get_or_create``. Also
  39. allows for multiple existing results.
  40. """
  41. lookup = dict(**kwargs)
  42. try:
  43. lookup["title__iexact"] = lookup.pop("title")
  44. except KeyError:
  45. pass
  46. try:
  47. return self.filter(**lookup)[0], False
  48. except IndexError:
  49. return self.create(**kwargs), True
  50. def delete_unused(self, keyword_ids=None):
  51. """
  52. Removes all instances that are not assigned to any object. Limits
  53. processing to ``keyword_ids`` if given.
  54. """
  55. if keyword_ids is None:
  56. keywords = self.all()
  57. else:
  58. keywords = self.filter(id__in=keyword_ids)
  59. keywords.filter(assignments__isnull=True).delete()