使模型的所有实例都成为事实

时间:2020-02-26 13:14:34

标签: python django

我有一个称为疾病的模型,该模型用于创建多个实例,例如疟疾,伤寒等。

模型

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',
}

因此,假设我在数据库中造成了许多这样的疾病:

enter image description here

将包含在词典中,如果以后再添加其他内容,则在被调用时将包含在词典中

1 个答案:

答案 0 :(得分:2)

我不确定为什么要让字典中的键和值是相同的值,但是可以通过以下方法实现所需的功能:

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