Login

RandomObjectManager

Author:
jjdelc
Posted:
March 2, 2011
Language:
Python
Version:
1.2
Tags:
random manager
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 for highlighting currently active page by adunar 6 years, 6 months ago
  2. Using manager methods by ubernostrum 8 years, 1 month ago
  3. Active / Inactive model manager by bendavis78 5 years, 10 months ago
  4. ActiveManager: filter objects depending on publication and/or expiration dates by haplo 6 years, 9 months ago
  5. Custom management command to list recent admin actions by pbx 5 years, 9 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.