Login

Seeded Randomized Querysets w/ Pagination Mixin

Author:
ScottBarkman
Posted:
February 25, 2015
Language:
Python
Version:
1.7
Score:
1 (after 1 ratings)

Mixin to support pagination when randomizing querysets.

Requirements: Postgres, Django Sessions

Note: This shouldn't be used on large complex datasets. It utilizes the relatively slow method of '?' randomized sorting. Use with caution.

Todo: MySQL support, Support for larger datasets

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import random
from django.db import connection


class RandomQuerysetMixin(object):
    """
        Filter/Sort by "random" without breaking pagination.
        Requirements:
            Postgres
            Django Sessions

        Todo:
            - Support for MySQL (replace setseed, w/ order by random(seed))
            - Support for larger datasets (get rid of '?')
    """
    randomize = True
    page_param = 'page'  # page slug to determine first page
    paginate_by = 16    # will be used to properly handle larger datasets
    large_dataset = False   # will be used to properly handle larger datasets

    seed = ''

    def get_queryset(self):
        if self.randomize:
            self.postgres_setseed()
            qs = super(RandomQuerysetMixin, self).get_queryset().order_by('?')
        else:
            qs = super(RandomQuerysetMixin, self).get_queryset()

        return qs

    def get(self, *args, **kwargs):
        page = self.request.GET.get(self.page_param)
        if not page or page == '1':
            self.generate_seed()

        self.seed = self.get_seed()

        return super(RandomQuerysetMixin, self).get(*args, **kwargs)

    def get_seed(self):
        if not self.request.session.get('seed'):
            return self.generate_seed()
        else:
            return self.request.session.get('seed')

    def generate_seed(self):
        # self.request.session['seed'] = random()
        self.request.session['seed'] = random.random()
        return self.request.session['seed']

    def postgres_setseed(self):
        cursor = connection.cursor()
        cursor.execute("SELECT setseed(%s);" % (self.seed,))
        cursor.close()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.