代码之家  ›  专栏  ›  技术社区  ›  sebpiq

Python/Django:在MySQL数据库上模拟多维层

  •  1
  • sebpiq  · 技术社区  · 14 年前

    我正在做一个Django项目,我需要在同一个数据上提供很多不同的可视化效果(例如 average of a value for each month , for each year / for a location

    总之,我需要一个python库:

    • 模拟多维数据库(OLAP风格会很好,因为我认为它非常方便:星型结构,等等)
    • 非侵入性的,因为我不能修改现有MySQL数据库上的任何内容
    • 易于使用,因为否则就没有必要用另一个来代替一些开销。
    4 回复  |  直到 14 年前
        1
  •  2
  •   sebpiq    14 年前

    好 啊。。。我终于想出了自己的解决办法( https://code.google.com/p/django-cube/ ),因为我找不到我想要的。

    class Instrument(models.Model):
        name = models.CharField(max_length=100)
    
    class Musician(models.Model):
        firstname = models.CharField(max_length=100)
        instrument = models.ForeignKey(Instrument)
    

    创建多维数据集:

    >>> c = Cube(['instrument__name', 'firstname'], Musician.objects.all(), len)
    ... #Cube(dimensions, queryset, aggregation_function)
    ... #You can use the Django field-lookup syntax for dates and foreign keys !!!
    

    沿一个(或多个)维度查询多维数据集:

    >>> c.measure_dict('firstname', 'instrument__name', full=False) == {
    ...     'Miles': {
    ...         'trumpet': {'measure': 1},
    ...         'sax': {'measure': 0},
    ...         'piano': {'measure': 0},
    ...     },
    ...     'John': {
    ...         'trumpet': {'measure': 0},
    ...         'sax': {'measure': 1},
    ...         'piano': {'measure': 4},
    ...     },
    ... }
    

    使用自定义模板标签等。。。

        2
  •  1
  •   lprsd    14 年前

    为什么不使用标准ORM聚合函数: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

    无论您认为性能会受到什么影响,您都可以将该字段反规范化。

        3
  •  0
  •   S.Lott    14 年前

    你有蟒蛇 defaultdict 字典。

    如果您的数据很小,只需查询所有数据,然后加载一堆包含计数和总和的字典。

    “星型模式”只是穷人的反向数据库,其中维度(即字典)引用行列表。您可以汇总这些行列表以创建摘要词典。

    d1_sum= defaultdict( int )
    d1_count= defaultdict( count )
    d2_sum = defaultdict( int )
    for row in MyFactTable.objects.all():
        d1_sum[row.attr1] += row.fact1
        d1_count[row.attr1] += 1
        d2_sum[row.attr2] += some_function( row.fact2 )
        etc.
    
        4
  •  0
  •   jjmontes    11 年前

    还有 http://cubes.databrewery.org/

    它可以在现有数据库模式的基础上工作,提供OLAP操作,并且易于使用。