dkoug Blog

Get random object from django database model

Django -- Posted on March 11, 2019

Custom manager to get random object from django database model

1
2
3
4
5
6
7
8
9
class RandomManager(models.Manager):

    def get_random(self, items=1):
        '''
        items is integer value
        '''
        if isinstance(items, int):
            return self.model.objects.order_by('?')[:items]
        return self.all()