如何在自定义类管理器的方法中获取上一个查询返回的数据?

时间:2021-07-22 16:20:22

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

1 个解决方案

#1


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

这看起来像你需要使用Django的内置count()函数docs.djangoproject.com/en/dev/ref/models/querysets

I do not see its use in your code.

我没有在你的代码中看到它的使用。

#1


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

这看起来像你需要使用Django的内置count()函数docs.djangoproject.com/en/dev/ref/models/querysets

I do not see its use in your code.

我没有在你的代码中看到它的使用。