RandomObjectManager

 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. CustomQueryManager by zvoase 4 years, 10 months ago
  2. ExtendibleModelAdminMixin by dokterbob 3 years, 6 months ago
  3. Function/Stored Procedure Manager by axiak 5 years, 11 months ago
  4. Ordered items in the database - alternative by Leonidas 5 years, 11 months ago
  5. FieldLevelPermissionsAdmin by buriy 5 years, 8 months ago

Comments

ffsffd (on March 8, 2011):

This seems pretty inefficient. Why not just use the queryset to perform this? See: http://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.QuerySet.order_by

myRandomObject = MyModel.objects.order_by('?')

Much nicer.

#

(Forgotten your password?)