获取饼图的数据

时间:2011-06-01 07:22:07

标签: python django

说,我有一个定义Car的模型,其中一个字段是'manufacturer'。例如:

class Car(models.Model):
    manufacturer = models.CharField(max_length=50)
    color = models.CharField(max_length=50)
    licence_plate = models.CharField(max_length=50)
    .
    .
    .

要绘制一个饼图,显示各个制造商的总数(使用matplotlib),我需要两个列表。一个包含制造商总数,另一个包含相应的制造商名称。所以我想最终得到这样的东西。

[516, 122, 131, 125, ...
['Ford','BMW','Mazda','Honda', ...

顺便说一下,我事先并不知道制造商的名字。

还有一件事,我只想展示前五大制造商。所有其他应归入名为“其他”的制造商。

我如何获得这些清单?

2 个答案:

答案 0 :(得分:0)

不确定这是否正确,但您需要以下内容:

from django.db.models import Count, Sum

num_taken = 5  # modify this if you want more/less than 5
query = Car.objects.values('manufacturer').annotate(num_cars=Count('manufacturer')).order_by('-num_cars')
top_cars = query[:num_taken]
others = query[num_taken:].aggregate(total=Sum('num_cars'))['total']
car_nums = [entry['num_cars'] for entry in top_cars] + [others]
car_manufactureres = [entry['manufacturerer'] for entry in top_cars] + ['Others']

答案 1 :(得分:0)

这是一个纯粹的python(你处理django的东西)解决方案。我给自己制作了一些汽车用品来测试代码。

from random import choice
from collections import defaultdict
from operator import itemgetter

manufacturers = ["Ford", "BMW", "Mazda", "Honda", "Volvo", "Saab", "Toyota"]
cars = [type("Car", (object,), {"manufacturer": choice(manufacturers)})
    for x in range(1000)]

count = defaultdict(int)
for car in cars:
    count[car.manufacturer] += 1

top = sorted(count.items(), key=itemgetter(1), reverse=True)
other = sum(x[1] for x in top[5:])
list1 = [x[0] for x in top[:5]] + ["other"]
list2 = [x[1] for x in top[:5]] + [other]

print list1
print list2