python - 避免多次查询多个计数

标签 python mysql django optimization query-optimization

我正在尝试找出一种从我的数据库中获取一些分析计数的好方法,而无需执行一堆查询并以某种方式执行一次

我现在拥有的是一个返回计数的函数

def get_counts(self):
    return {
        'item_one_counts'  : self.items_one.count(),
        'item_two_counts'  : self.items_two.count(),
        'item_three_count' : self.items_three.count(),
    }

我知道我可以使用原始查询执行此操作,该查询执行 SELECT as count1,2,3 FROM table X

有没有更像 django 的方法来做到这一点?

最佳答案

如果您想在实例方法中获取计数,您就晚了一点。最简单的优化方法是在初始查询中使用注释:

obj = MyModel.objects.annotate(item_one_count=Count('items_one')) \
             .annotate(item_two_count=Count('items_two')) \
             .annotate(item_three_count=Count('items_three')) \
             .get(...)

另一个好的优化是缓存结果,例如:

MyModel(models.Model):
    def get_item_one_count(self):
        if not hasattr(self, '_item_one_count'):
            self._item_one_count = self.items_one.count()
        return self._item_one_count

    ...

    def get_counts(self):
        return {
                'item_one_counts'  : self.get_item_one_count(),
                'item_two_counts'  : self.get_item_two_count(),
                'item_three_count' : self.get_item_three_count(),
        }

结合这些方法(即 .annotate(_item_one_count=Count('items_one'))),您可以在控制查询时将计数优化为单个查询,同时进行回退方法,以防您无法注释结果。

另一种选择是在您的模型管理器中执行注释,但您将无法再对查询进行细粒度控制。

关于python - 避免多次查询多个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541854/

相关文章:

django - SQLAlchemy 是否有 Django 的spectrdb 等效项?

python - 在给定的 docker-compose 容器内执行 Python 脚本

php - Mysql查询: switch if record come from table news or news_collect

sql - 将 get_absolute_url 组合成 django 中的原始 SQL 语句

php - CodeIgniter Datatable加入搜索(json_encoded数据)

Mysql join - 检查具有某些列值的不存在的行

python - Django shell 中的奇怪字符,箭头键不起作用

python - 基于输入行的 pandas long_to_wide 方法

python - 使用一些偏移量从服务器读取文件

Python:动态 "from"导入