[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 = {'month': connection.ops.date_trunc_sql('month', 'date_created')}
Foobar.objects.extra(select=select).values('month').annotate(number ...
more ...


[python]Windows 下的 ANSI 编码

Date Category python

Windows 下用记事本保存文件时有个 ANSI 编码,那么如何用 python 保存一个 ANSI 编码的文件呢?

python 中使用 mbcs 编码(Windows only)表示 ANSI:

with open('hello.txt', 'w') as f:
    f.write(u'你好'.encode('mbcs'))

执行上面的代码,就可以创建一个 ANSI 编码的文件。

ANSI == Windows 本地编码

在简体中文 Windows 系统中:ansi == gbk :

>>> u'你好'.encode('mbcs')
'\xc4\xe3\xba\xc3 ...
more ...