Login

Chainable custom query manager for randomize.

Author:
I159
Posted:
September 21, 2011
Language:
Python
Version:
Not specified
Tags:
queryset related-models randomize custom-manager
Score:
0 (after 0 ratings)

This manager is based on the economical method of randomization. It usable in related models. For support this behavior required to be defined as default manger.

 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
from django.db import models

import random

class RandomQueryset(models.query.QuerySet):
    """Custom queryset"""
    
    def randomize(self):
        """Returns random object from given model
         without 'shot the foot' ['?'][0]"""       
        count = self.count()
        random_index = random.randint(0, count - 1)
        return self.all()[random_index]


class RandomManager(models.Manager):
    """Custom manager, returns RandomQueryset instance. 
    Usable for related objects, required to be defined as default manager."""
    
    use_for_related_fields = True
    
    def get_query_set(self):
        return RandomQueryset(self.model, using=self._db)
    
    def randomize(self):
        return self.get_query_set().randomize()


In use:

In [1]: from myapp.models import PostPages
In [2]: post = PostPages.objects.filter(image_gallery__isnull=False).distinct().randomize()
In [3]: post.image_gallery.randomize()
Out[3]: <Image: /site_media/media/img/vkrasa_gomukhasana.jpg>

More like this

  1. Custom Model Manager Chaining by hunterford 4 years, 10 months ago
  2. Easier custom Model Manager Chaining by gsakkis 4 years, 10 months ago
  3. Tatsypie: additional list endpoints for custom Model's manager methods by migajek 2 years, 6 months ago
  4. Fetching top items by ubernostrum 8 years, 2 months ago
  5. Model with random ID by jobs@flowgram.com 6 years, 11 months ago

Comments

Please login first before commenting.