from django.template.loader import render_to_string from django.db import models from django.db.models import Count, Sum from django.core.urlresolvers import reverse from boards.models import Thread from boards.models.base import Viewable __author__ = 'neko259' class TagManager(models.Manager): def get_not_empty_tags(self): """ Gets tags that have non-archived threads. """ tags = self.annotate(Count('threads')) \ .filter(threads__count__gt=0).order_by('name') return tags class Tag(models.Model, Viewable): """ A tag is a text node assigned to the thread. The tag serves as a board section. There can be multiple tags for each thread """ objects = TagManager() class Meta: app_label = 'boards' ordering = ('name',) name = models.CharField(max_length=100, db_index=True) threads = models.ManyToManyField(Thread, null=True, blank=True, related_name='tag+') def __str__(self): return self.name def is_empty(self): """ Checks if the tag has some threads. """ return self.get_thread_count() == 0 def get_thread_count(self): return self.threads.count() def get_post_count(self, archived=False): """ Gets posts count for the tag's threads. """ posts_count = 0 threads = self.threads.filter(archived=archived) if threads.exists(): posts_count = threads.annotate(posts_count=Count('replies')) \ .aggregate(posts_sum=Sum('posts_count'))['posts_sum'] if not posts_count: posts_count = 0 return posts_count def get_url(self): return reverse('tag', kwargs={'tag_name': self.name}) def get_view(self, *args, **kwargs): return render_to_string('boards/tag.html', { 'tag': self, })