Django有一些即将发布的OLAP功能.
阅读http://www.eflorenzano.com/blog/post/secrets-django-orm/
http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html,也
如果您首先拥有适当的星型模式设计,那么一维结果可以具有以下形式.
from myapp.models import SomeFact
from collections import defaultdict
facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that )
myAggregates = defaultdict( int )
for row in facts:
myAggregates[row.dimension3__attribute] += row.someMeasure
Run Code Online (Sandbox Code Playgroud)
如果要创建二维摘要,则必须执行以下操作.
facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that )
myAggregates = defaultdict( int )
for row in facts:
key = ( row.dimension3__attribute, row.dimension4__attribute )
myAggregates[key] += row.someMeasure
Run Code Online (Sandbox Code Playgroud)
要计算多个SUM和COUNT以及什么不是,你必须做这样的事情.
class MyAgg( object ):
def __init__( self ):
self.count = 0
self.thisSum= 0
self.thatSum= 0
myAggregates= defaultdict( MyAgg )
for row in facts:
myAggregates[row.dimension3__attr].count += 1
myAggregates[row.dimension3__attr].thisSum += row.this
myAggregates[row.dimension3__attr].thatSum += row.that
Run Code Online (Sandbox Code Playgroud)
这 - 乍一看似乎效率低下.您正在浏览事实表,返回许多行,然后您将在应用程序中进行聚合.
在某些情况下,这可能比RDBMS的本机sum/group_by 更快.为什么?您使用的是简单的映射,而不是RDBMS通常必须使用的更复杂的基于排序的分组操作.是的,你得到了很多行; 但你得到的却少了.
这样做的缺点是它不像我们想的那样具有说服力.它的优点是它是纯Django ORM.