python - 自定义类管理器的方法中如何获取之前查询返回的数据?

标签 python django oop django-managers

我使用可链接方法开发自定义管理器类。有问题。我需要随机化过滤查询。为了获得随机记录,我需要过滤和不同记录的计数。但我不知道如何得到它。相反,我有所有记录的计数。

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()

使用:

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

>>> posts.randomize()

迟早我会收到错误,因为该计数超出了当前查询中的记录数。

IndexError: list index out of range

最佳答案

您要求我发布一个问题作为答案,所以就开始吧。

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

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

关于python - 自定义类管理器的方法中如何获取之前查询返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7475258/

相关文章:

django - 单元测试权限

Python 输入 : Describe common properties

python - 将行追加到 NumPy 记录数组

python - 为什么我会收到错误的文件描述符错误?

python - 编程错误: Incorrect number of bindings supplied

python - 在 Django 中获取彼此相邻的两个对象

javascript - jQuery keyup 事件被激活多次,每次触发都会加倍

c# - Curly Brace 出现在不应该出现的地方

c++ - 什么时候在 C++ 中使用 struct over class

Python - 从 CSV 文件创建多个文件夹