Login

RandomObjectManager

Author:
jjdelc
Posted:
March 2, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Manager Mixin to implement get_random() in your models. You can override get_objects to tune the queriset

To use, define your class:

class MyManager(models.Manager, RandomObjectManager): DEFAULT_NUMBER = 5 # I can change that

def get_objects(self):
    return self.filter(active=True) # Only active models plz

class MyModel(models.Model): active = models.BooleanField() objects = MyManager()

Now you can do: MyModel.objects.get_random()

 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
# -*- coding: utf-8 -*-

from random import sample

class RandomObjectManager(object):
    """
    Manager Mixin to implement get_random() in your models.
    You can override get_objects to tune the queriset

    To use, define your class:

    class MyManager(models.Manager, RandomObjectManager):
        DEFAULT_NUMBER = 5 # I can change that

        def get_objects(self):
            return self.filter(active=True) # Only active models plz

    class MyModel(models.Model):
        active = models.BooleanField()
        objects = MyManager()

    Now you can do:
    MyModel.objects.get_random()

    """

    DEFAULT_NUMBER = 3

    def get_objects(self):
        return self.all()

    def get_random(self, number=DEFAULT_NUMBER):
        """
        Returns a set of random objects
        """
        ids = self.get_objects().values_list('id', flat=True)
        amount = min(len(ids), number)
        picked_ids = sample(ids, amount)
        return self.filter(id__in=picked_ids)

More like this

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

Comments

victorhooi (on July 24, 2013):

Hi,

@ffsffd: The reason is that using the "?" operator as you suggested is incredibly inefficient (something that the Django documentation notes).

It will iterate over every row in the database, generating a random integer in a new column.

Then, it will sort by that column - and this is actually a worst-case scenario for the sort, since those integers are by definition random.

#

Please login first before commenting.