tag.py
76 lines
| 2.0 KiB
| text/x-python
|
PythonLexer
|
r692 | from django.template.loader import render_to_string | ||
|
r386 | from django.db import models | ||
|
r928 | from django.db.models import Count | ||
|
r692 | from django.core.urlresolvers import reverse | ||
|
r732 | |||
|
r692 | from boards.models.base import Viewable | ||
|
r973 | from boards.utils import cached_result | ||
|
r385 | |||
|
r732 | |||
|
r385 | __author__ = 'neko259' | ||
class TagManager(models.Manager): | ||||
def get_not_empty_tags(self): | ||||
|
r623 | """ | ||
Gets tags that have non-archived threads. | ||||
""" | ||||
|
r928 | return self.filter(thread__archived=False)\ | ||
|
r929 | .annotate(num_threads=Count('thread')).filter(num_threads__gt=0)\ | ||
|
r932 | .order_by('-required', 'name') | ||
|
r385 | |||
|
r692 | class Tag(models.Model, Viewable): | ||
|
r385 | """ | ||
|
r398 | 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 | ||||
|
r385 | """ | ||
objects = TagManager() | ||||
class Meta: | ||||
app_label = 'boards' | ||||
|
r649 | ordering = ('name',) | ||
|
r385 | |||
|
r983 | name = models.CharField(max_length=100, db_index=True, unique=True) | ||
required = models.BooleanField(default=False, db_index=True) | ||||
|
r385 | |||
|
r875 | def __str__(self): | ||
|
r385 | return self.name | ||
|
r908 | def is_empty(self) -> bool: | ||
|
r623 | """ | ||
Checks if the tag has some threads. | ||||
""" | ||||
|
r606 | return self.get_thread_count() == 0 | ||
|
r385 | |||
|
r908 | def get_thread_count(self) -> int: | ||
return self.get_threads().count() | ||||
|
r385 | |||
|
r692 | def get_url(self): | ||
return reverse('tag', kwargs={'tag_name': self.name}) | ||||
|
r908 | def get_threads(self): | ||
|
r928 | return self.thread_set.order_by('-bump_time') | ||
|
r922 | |||
def is_required(self): | ||||
return self.required | ||||
def get_view(self): | ||||
link = '<a class="tag" href="{}">{}</a>'.format( | ||||
|
r928 | self.get_url(), self.name) | ||
|
r922 | if self.is_required(): | ||
link = '<b>{}</b>'.format(link) | ||||
return link | ||||
def get_search_view(self, *args, **kwargs): | ||||
return render_to_string('boards/tag.html', { | ||||
|
r928 | 'tag': self, | ||
}) | ||||
|
r960 | |||
|
r973 | @cached_result | ||
|
r960 | def get_post_count(self): | ||
return self.get_threads().aggregate(num_posts=Count('post'))['num_posts'] | ||||