python - 将模型的所有实例放入对象
问题描述
我有一个名为疾病的模型,我用它来创建多个实例,如疟疾、伤寒等。
模型
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',
}
所以,假设我在我的数据库中创造了许多这样的疾病:
将包含在字典中,如果以后添加其他,它们将在调用时包含在字典中
解决方案
我不确定为什么您希望字典中的键和值具有相同的值,但您可以通过以下方式实现您想要的:
duration_choices = {i.name: i.name for i in Sickness.objects.all()}
推荐阅读
- python-3.x - 对于具有负整数的列表,默认情况下对集合进行反向排序
- c# - 带有复选框的 C# WPF 目录树视图:检查构建项目失败,PropertyChanged 为空
- asp.net - StackExchange.Redis ConnectionMultiplexer 池用于同步方法
- javascript - 从 JS 客户端上的 Flask 服务器接收 xlsx 文件
- java - 删除映射方法不适用于弹簧
- html - 使用 zurb 基础代码的手风琴切换图标
- javascript - 合并排序数组
- machine-learning - 比较两个分布与桶之间的关系
- mysql - 创建显示飞行员名单的视图
- r - CCF 绘图函数循环