1

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
I159
  • 29,741
  • 31
  • 97
  • 132
  • 1
    Are you using Django's built in count() function? https://docs.djangoproject.com/en/dev/ref/models/querysets/ I don't see .count(). Why not take a count for filtered and un-filtered? – octopusgrabbus Sep 19 '11 at 18:12
  • I use aggregate and Count `from django.db.models import Count`. So how to take count of filtered records in `randomize()` method? – I159 Sep 19 '11 at 18:26
  • I'm having trouble understanding what the filter is. – octopusgrabbus Sep 19 '11 at 19:10
  • In posts model I've got m2m field to model containing pictures. The filter checks, is m2m field filled, i.e. is there a pictures in the post. – I159 Sep 20 '11 at 07:38
  • @octopusgrabbus, thanks a lot! I have replaced `aggregate(count = Count('id'))` by `count()`. It works native! Make it answer, please. – I159 Sep 20 '11 at 09:47

1 Answers1

1

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.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131