提取统计数据

时间:2013-07-15 20:52:35

标签: python django

我有这两个模型:

class Log(models.Model):
    ...
    country = models.ForeignKey(Country, null=True, blank=True)
    ...
    user = models.ForeignKey('auth.User')


class Country(models.Model):
    name = models.CharField(max_length=50)
    alpha_2_code = models.CharField("Alpha-2 code", max_length=2, unique=True)
    alpha_3_code = models.CharField("Alpha-3 code", max_length=3, unique=True)
    numeric_code = models.PositiveSmallIntegerField("Numeric code", max_length=3, unique=True)
    order = models.SmallIntegerField(max_length=3)
    continent = models.ForeignKey(Continent)

    def __unicode__(self):
        return self.name

我想要做的是根据日志条目显示Google Map Chart,所以我应该传递给模板的是这样的:

    function drawRegionsMap() {
        var data = google.visualization.arrayToDataTable([
            ['Country', 'Popularity'],
            ['Germany', 200],
            ['United States', 300],
            ['Brazil', 400],
            ['Canada', 500],
            ['France', 600],
            ['RU', 700]
        ]);

提取数据并将数据传递给模板的最快方法是什么?

1 个答案:

答案 0 :(得分:3)

我假设popularity被定义为count模型的SQL Log,按国家/地区分组。如我错了请纠正我。有关详细信息,请参阅aggregation documentation

from django.db.models import Count
queryset = Log.objects.values('country__name').annotate(popularity=Count('country__name'))

然后在你的模板中你会做:

var data = google.visualization.arrayToDataTable([
        ['Country', 'Popularity'],
        {% for log in queryset %}
        ['{{ log.country.name }}', {{ log.popularity }} ] {% if not forloop.last %},{% endif %}
        {% endfor %}
    ]);

请注意,在模板中,我正在检查最后一次迭代的forloop,如果是最后一次迭代,则不包括尾随逗号。