遍历django的实例

时间:2018-10-01 16:29:00

标签: 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 :(得分:2)

我建议您通读django的文档,以创建模型,通过django的python shell查询数据库以及有关数据库/关系字段之间的关系。

Documentation on making queries to the database

Documentation on database relationships

Documentation on models

针对您的问题,我将创建2个模型:人,疾病

class Person(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=6, choices = GENDER_CHOICES)
    name = models.CharField(max_length=20)

然后是疾病的模型,由于人们患有疾病而不是相反,因此我将疾病模型作为人的外键

class Disease(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    DISEASE_CHOICES = (
        ('CHOLERA', 'Cholera'),
        ('HIV', 'HIV'),
        ('MALARIA', 'Malaria'),
        ('TYPHOID', 'Typhoid'),
        ('MEASLES', 'Measles'),
    )
    disease = models.CharField(max_length=20, choices=DISEASE_CHOICES)

为这些模型创建实例后,您可以在python shell中调用它并获得所需的结果:

for i in Disease.objects.all():
    if i.person.gender == 'M':
         if i.disease in males:
             males[i.disease] += 1
         else:
             males.update({i.disease:1})
     elif i.person.gender == 'F':
         if i.disease in females:
             females[i.disease] += 1
         else:
             females.update({i.disease:1})

在我的测试案例中,输出为:

>>> males
{'HIV': 2, 'MALARIA': 2, 'TYPHOID': 2}
>>> females
{'HIV': 2}

注意:在执行上面的循环之前,您应该定义空字典malesfemales

您可以在运行此命令后获得想要的结果:

for k in males:
    'Males ' + k + ' ' + str(males[k])

以我为例的结果

'Males HIV 2'
'Males MALARIA 2'
'Males TYPHOID 2'

由您决定将其重新制成方法。