[python]for 循环中的局部变量陷阱

先看一段代码:

>>> x = 10
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
2

从这段代码,我们可以知道:for 循环中用于循环主体的变量会影响上下文的局部变量。

所以,类似下面这样的代码就会有问题:

for x in foo:
    # ...
    bar = [ x for x in foobar]
    n = x['abc']   # error
    # ...
more ...

[django]按天分组统计数据

假设有以下 model:

class Foobar(models.Model):
    name = models.CharField(max_length=100)
    date_created = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.name

按天统计数量的代码如下:

from django.db import connection
from django.db.models import Count

select = {'day': connection.ops.date_trunc_sql('day', 'date_created')}
Foobar.objects.extra(select=select).values('day').annotate(number ...
more ...

[django]按小时分组统计数据

假设有以下 model:

class Foobar(models.Model):
    name = models.CharField(max_length=100)
    date_created = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.name

按小时统计数量的代码如下:

from collections import defaultdict
from django.db import connection
from django.db.models import Count

select = {'hour': connection.ops.date_trunc_sql('hour', 'date_created')}
result = Foobar.objects.extra(select ...
more ...