在django管理员中分组

时间:2018-10-01 19:17:09

标签: python django

models.py

from django.db import models
from collections import Counter
from django.db.models import Count
from itertools import groupby
Gender = (
    ('Male', 'MALE'),
    ('Female', 'FEMALE'),
)

Diseases = (
    ('Cholera', 'CHOLERA'),
    ('HIV', 'HIV'),
    ('Malaria', 'MALARIA'),
    ('Typhoid', 'TYPHOID'),
    ('Measles', 'MEASLES'),
)


class MyModel(models.Model):
    Gender = models.CharField(max_length=16, choices=Gender, default='MALE')
    Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA')
    vote = models.IntegerField(default=0)

    def __str__(self):
            r=0
            return u'%s %s' % (self.Gender, self.Diseases)

现在,这将在管理Django面板中返回

Male Measles
Male Measles
Male Cholera
Female Cholera
Female Typhoid
Female Typhoid

但是我想对其进行分组,使其看起来像这样:

Male malaria 2
Male Measles 2
Female Typhoid 3 

在此管理面板中,而不是像现在一样列出所有内容

1 个答案:

答案 0 :(得分:0)

您可以利用valuesannotate函数对值进行分组

MyModel.objects.values('Gender, Diseases').annotate(Count('Gender'), Count('Diseases'))

但是,如果您希望能够编辑数据,则在管理面板中对某些内容进行分组实际上没有任何意义。分组将删除每个元素的标识/主键,并使它无法在对象视图中实际选择一个元素。