# HG changeset patch # User neko259 # Date 2015-07-29 18:40:46 # Node ID 93f2906af979b18e4bfb832fba63b9e2b94fb236 # Parent be5f9d10ae6baa92e0439a1932ce5386bbf45b2b Don't return posts with the same image in random view diff --git a/boards/models/image.py b/boards/models/image.py --- a/boards/models/image.py +++ b/boards/models/image.py @@ -2,9 +2,12 @@ import hashlib import os from random import random import time + from django.db import models from django.template.defaultfilters import filesizeformat + from boards import thumbs +import boards from boards.models.base import Viewable __author__ = 'neko259' @@ -39,6 +42,9 @@ class PostImageManager(models.Manager): md5.update(chunk) return md5.hexdigest() + def get_random_images(self, count): + return self.order_by('?')[:count] + class PostImage(models.Model, Viewable): objects = PostImageManager() @@ -108,3 +114,7 @@ class PostImage(models.Model, Viewable): str(self.hash), str(self.pre_width), str(self.pre_height), str(self.width), str(self.height), full=self.image.url, image_meta=metadata) + + def get_random_associated_post(self): + return boards.models.Post.objects.filter(images__in=[self])\ + .order_by('?').first() diff --git a/boards/templates/boards/random.html b/boards/templates/boards/random.html --- a/boards/templates/boards/random.html +++ b/boards/templates/boards/random.html @@ -8,17 +8,17 @@ {% block content %} - {% if posts %} + {% if images %}
- {% for post in posts %} + {% for image in images %} {% if forloop.counter|divisibleby:"3" %}
diff --git a/boards/views/random.py b/boards/views/random.py --- a/boards/views/random.py +++ b/boards/views/random.py @@ -1,16 +1,13 @@ from django.shortcuts import render -from django.template import RequestContext from django.views.generic import View -from django.db.models import Count -from boards.models import Post -from boards.mdx_neboard import Parser +from boards.models import PostImage __author__ = 'neko259' TEMPLATE = 'boards/random.html' -CONTEXT_POSTS = 'posts' +CONTEXT_IMAGES = 'images' RANDOM_POST_COUNT = 9 @@ -19,10 +16,7 @@ class RandomImageView(View): def get(self, request): params = dict() - posts = Post.objects.annotate(images_count=Count( - 'images')).filter(images_count__gt=0).order_by('?')\ - [:RANDOM_POST_COUNT] - - params[CONTEXT_POSTS] = posts + params[CONTEXT_IMAGES] = PostImage.objects.get_random_images( + RANDOM_POST_COUNT) return render(request, TEMPLATE, params)