Skip to content

Instantly share code, notes, and snippets.

@jjdelc
Created March 3, 2011 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjdelc/852323 to your computer and use it in GitHub Desktop.
Save jjdelc/852323 to your computer and use it in GitHub Desktop.
Django RandomObjectManager
# -*- 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment