我正在使用 Django,并且我有一个类来定义一些常量(我在我的模型中使用它)
class ArticleStatus:
OPEN = 'open'
CLOSED = 'closed'
BLOCKED = 'blocked'
CHOICES = (
(OPEN, 'Open'),
(CLOSED, 'Closed'),
(BLOCKED, 'Blocked')
)
在我看来,我有一个查询集,它给了我这个结果:
context['total'] = [
{'status': 'open', 'total': 102},
{'status': 'closed', 'total': 150},
{'status': 'blocked', 'total': 24}
]
我的目标是将状态值从常量转换为更易读的值。我用下面的代码做到了这一点
for i in range(0, len(context['total'])):
status = context['total'][i]['status']
for status_const in ArticleStatus.CHOICES:
if status == status_const[0]:
context['total'][i]['status'] = status_const[1]
转换后的结果为:
context['total'] = [
{'status': 'Open', 'total': 102},
{'status': 'Closed', 'total': 150},
{'status': 'Blocked', 'total': 24}
]
但是,我的代码看起来效率不是很高,我想问是否有人有更好的解决方案?
最佳答案
一种方法是使用 for
循环来迭代列表并使用预先计算的字典映射:
choice_map = dict(ArticleStatus.CHOICES)
for item in context['total']:
item['status'] = choice_map[item['status']]
print(context)
{'total': [{'status': 'Open', 'total': 102},
{'status': 'Closed', 'total': 150},
{'status': 'Blocked', 'total': 24}]}
关于python - 将字典中的值替换为常量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50220182/