Question

I developing a custom manager class with chainable method. Got a problem. I need to randomize filtered query. To get a random record I need a count of filtered and distinct records. But I don't know how to get it. On the contrary, I have a count of all records.

class RandomQueryset(models.query.QuerySet):

    def randomize(self):        
        count = self.aggregate(count=Count('id'))['count']
        random_index = random.randint(0, count - 1)
        return self.all()[random_index]    


class RandomManager(models.Manager):

    def get_query_set(self):
        return RandomQueryset(self.model, using=self._db)

    def randomize(self):
        return self.get_query_set().randomize()

Using:

>>> posts = PostPages.random_objects.filter(image_gallery__isnull=False).distinct()

>>> posts.randomize()

Sooner or later I get an error because that count exceeds the number of records in the current query.

IndexError: list index out of range
Was it helpful?

Solution

You've asked me to post one of my questions as an answer, so here goes.

This looks like you need to use Django's built-in count() function docs.djangoproject.com/en/dev/ref/models/querysets

I do not see its use in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top