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