Login

Chainable custom query manager for randomize.

Author:
I159
Posted:
September 21, 2011
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 8 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.