How to get the data returned by the previous query in the method of custom class manager?
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
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.
精彩评论