如何处理django分组选择?

时间:2014-12-19 12:15:59

标签: django python-2.7 django-models choice

有这种django选择:

MEDIA_CHOICES = (
    ('Audio', (
        ('vinyl', 'Vinyl'),
        ('cd', 'CD'),
    )
    ),
    ('Video', (
        ('vhs', 'VHS Tape'),
        ('dvd', 'DVD'),
    )
    ),
    ('unknown', 'Unknown'),
)

如何访问类别的子组(例如,获取音频选项)?我如何迭代集合?,如何直接获取叶子节点,如Vinyl?

1 个答案:

答案 0 :(得分:1)

内置类型dict可以从元组列表构建。

>>> MEDIA_CHOICES_D = dict(MEDIA_CHOICES)
>>> MEDIA_CHOICES_D.keys()
['unknown', 'Audio', 'Video']
>>> audio = MEDIA_CHOICES_D['Audio']
>>> audio
(('vinyl', 'Vinyl'), ('cd', 'CD'))
>>> audio_d = dict(audio)
>>> audio_d['vinyl']
'Vinyl'
>>> for k, v in audio_d.iteritems(): print '%s -> %s' % (k, v)
... 
vinyl -> Vinyl
cd -> CD
>>>