首页 > 解决方案 > 将模型的所有实例放入对象

问题描述

我有一个名为疾病的模型,我用它来创建多个实例,如疟疾、伤寒等。

模型

class Sickness(models.Model):
    name = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.name

拜托,我怎样才能把它变成这样的字典形式,名字将被输入字典。

duration_choices = {
    'malaria':'malaria',
    'typhod':'typhod',
    'cough':'cough',
    'headache':'headache',
    'stomach gas':'stomach gas',
}

所以,假设我在我的数据库中创造了许多这样的疾病:

在此处输入图像描述

将包含在字典中,如果以后添加其他,它们将在调用时包含在字典中

标签: pythondjango

解决方案


我不确定为什么您希望字典中的键和值具有相同的值,但您可以通过以下方式实现您想要的:

duration_choices = {i.name: i.name for i in Sickness.objects.all()}

推荐阅读