自定义类管理器的方法中如何获取之前查询返回的数据?
我使用可链接方法开发自定义管理器类。有问题。我需要随机化过滤查询。为了获得随机记录,我需要过滤和不同记录的计数。但我不知道如何得到它。相反,我有所有记录的计数。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要求我发布我的一个问题作为答案,所以就这样吧。
看起来您需要使用 Django 的内置 count() 函数 docs.djangoproject。 com/en/dev/ref/models/querysets
我没有在您的代码中看到它的使用。
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.