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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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.