Created
March 3, 2011 04:16
-
-
Save jjdelc/852323 to your computer and use it in GitHub Desktop.
Django RandomObjectManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment