# HG changeset patch # User neko259 # Date 2015-08-11 10:01:39 # Node ID 50888044d73eed5bdfd03268232d2d740443d3b7 # Parent fe04a375912984dd6a197a438159e69a371006fc Speed up getting tag's random image diff --git a/boards/models/image.py b/boards/models/image.py --- a/boards/models/image.py +++ b/boards/models/image.py @@ -118,8 +118,6 @@ class PostImage(models.Model, Viewable): str(self.pre_height), str(self.width), str(self.height), full=self.image.url, image_meta=metadata) - def get_random_associated_post(self, tags=None): + def get_random_associated_post(self): posts = boards.models.Post.objects.filter(images__in=[self]) - if tags is not None: - posts = posts.filter(threads__tags__in=tags) return posts.order_by('?').first() diff --git a/boards/models/tag.py b/boards/models/tag.py --- a/boards/models/tag.py +++ b/boards/models/tag.py @@ -5,7 +5,7 @@ from django.core.urlresolvers import rev from boards.models.base import Viewable from boards.utils import cached_result - +import boards __author__ = 'neko259' @@ -90,3 +90,9 @@ class Tag(models.Model, Viewable): def get_description(self): return self.description + + def get_random_image_post(self): + return boards.models.Post.objects.annotate(images_count=Count( + 'images')).filter(images_count__gt=0, threads__tags__in=[self])\ + .order_by('?').first() + diff --git a/boards/templates/boards/all_threads.html b/boards/templates/boards/all_threads.html --- a/boards/templates/boards/all_threads.html +++ b/boards/templates/boards/all_threads.html @@ -39,10 +39,12 @@ {% if tag %}
- + {% with image=random_image_post.images.first %} + + {% endwith %}

diff --git a/boards/views/tag_threads.py b/boards/views/tag_threads.py --- a/boards/views/tag_threads.py +++ b/boards/views/tag_threads.py @@ -12,7 +12,6 @@ PARAM_HIDDEN_TAGS = 'hidden_tags' PARAM_TAG = 'tag' PARAM_IS_FAVORITE = 'is_favorite' PARAM_IS_HIDDEN = 'is_hidden' -PARAM_RANDOM_IMAGE = 'random_image' PARAM_RANDOM_IMAGE_POST = 'random_image_post' __author__ = 'neko259' @@ -49,9 +48,7 @@ class TagView(AllThreadsView, Dispatcher params[PARAM_IS_FAVORITE] = fav_tag_names is not None and tag.name in fav_tag_names params[PARAM_IS_HIDDEN] = hidden_tag_names is not None and tag.name in hidden_tag_names - image = PostImage.objects.get_random_images(1, tags=[tag])[0] - params[PARAM_RANDOM_IMAGE] = image - params[PARAM_RANDOM_IMAGE_POST] = image.get_random_associated_post(tags=[tag]) + params[PARAM_RANDOM_IMAGE_POST] = tag.get_random_image_post() return params