##// END OF EJS Templates
Optimized tag DB queries
neko259 -
r928:b28a856f default
parent child Browse files
Show More
@@ -1,9 +1,8 b''
1 1 from django.template.loader import render_to_string
2 2 from django.db import models
3 from django.db.models import Count, Sum
3 from django.db.models import Count
4 4 from django.core.urlresolvers import reverse
5 5
6 from boards.models import Thread
7 6 from boards.models.base import Viewable
8 7
9 8
@@ -17,13 +16,8 b' class TagManager(models.Manager):'
17 16 Gets tags that have non-archived threads.
18 17 """
19 18
20 not_empty_tags = list()
21 tags = self.order_by('-required', 'name')
22 for tag in tags:
23 if tag.get_thread_count() > 0:
24 not_empty_tags.append(tag)
25
26 return not_empty_tags
19 return self.filter(thread__archived=False)\
20 .annotate(num_threads=Count('thread')).filter(num_threads__gt=0)
27 21
28 22
29 23 class Tag(models.Model, Viewable):
@@ -54,34 +48,16 b' class Tag(models.Model, Viewable):'
54 48 def get_thread_count(self) -> int:
55 49 return self.get_threads().count()
56 50
57 def get_post_count(self, archived=False):
58 """
59 Gets posts count for the tag's threads.
60 """
61
62 posts_count = 0
63
64 threads = self.get_threads().filter(archived=archived)
65 if threads.exists():
66 posts_count = threads.annotate(posts_count=Count('replies')) \
67 .aggregate(posts_sum=Sum('posts_count'))['posts_sum']
68
69 if not posts_count:
70 posts_count = 0
71
72 return posts_count
73
74 51 def get_url(self):
75 52 return reverse('tag', kwargs={'tag_name': self.name})
76 53
77 54 def get_threads(self):
78 return Thread.objects.filter(tags__in=[self]).order_by('-bump_time')
55 return self.thread_set.order_by('-bump_time')
79 56
80 57 def is_required(self):
81 58 return self.required
82 59
83 60 def get_view(self):
84 #prefix = '##' if self.is_required() else '#'
85 61 link = '<a class="tag" href="{}">{}</a>'.format(
86 62 self.get_url(), self.name)
87 63 if self.is_required():
General Comments 0
You need to be logged in to leave comments. Login now