我正在尝试找出一种从我的数据库中获取一些分析计数的好方法,而无需执行一堆查询并以某种方式执行一次
我现在拥有的是一个返回计数的函数
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/