如何对模型属性进行分组

时间:2016-02-22 16:29:32

标签: python django models

我有一个课程,我希望在不定期点击数据库的情况下显示每个Car的所有模型。所以我创建了一个dict,但我不认为这是最好的解决方案。如何更专业地解决这个问题?

class Car(models.Model):

    name = models.CharField(max_length=100)
    model = models.CharField(max_length=100)

    def __str__(self):
        return self.name + '/' + self.model


def catatlog(request):

    cars = {}
    all_cars = Car.objects.all().order_by('name')
    for i in all_cars:
        if i.name not in cars.keys():
            cars[i.name] = [i.model]
        else:
            cars[i.name].append(i.model)
    return render(request, 'index.html', {'cars':cars})

1 个答案:

答案 0 :(得分:2)

您可以改为使用defaultdict

from collections import defaultdict

def catatlog(request):
    cars = defaultdict(list)
    for i in Car.objects.all():
        cars[i.name].append(i.model)
    return render(request, 'index.html', {'cars':cars})