【问题标题】:Avoiding multiple queries for multiple counts避免多次查询多个计数
【发布时间】:2015-02-16 23:04:23
【问题描述】:

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

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

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-y 方式来做到这一点?

【问题讨论】:

  • 你检查我的解决方案了吗?

标签: python mysql django optimization query-optimization


【解决方案1】:

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

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'))),当您可以控制查询时,您可以将计数优化到单个查询中,同时在您无法注释结果的情况下使用回退方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多