检索组ChoiceField的密钥
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
class ressource(models.Model):
....
media = models.CharField(max_length=50, choices=MEDIA_CHOICES)
在现场媒体中,我有乙烯基或cd或vhs或dvd ...但是如何检索音频,视频,未知?
答案 0 :(得分:0)
您应向我们证明更多细节。首先,选择应该是iterable
对象(例如,在您的情况下为tuple
),但是您的tuple
在您的情况下非常复杂(Django无法处理该对象)。您应该通过这样的选择。
CHOICES = (
('key', 'value') # key will be inserted in database (and validation purposes), and value is just for representation purposes.
)
LANGUAGES = (
('python', 'Python'),
('js', 'JS'),
('ruby', 'Ruby'),
)
想象一下,您正在尝试从数据库中检索对象。
class ressource(models.Model):
''' This is your model '''
media = models.CharField(max_length=50, choices=MEDIA_CHOICES)
res = ressource.objects.get(pk=1) # retrieve data from database.
print(res.media) # returns string object. you will read actual value of media field
''' But if you want to read all available choices on this field, Django provide as _meta api. You can use it very nice way '''
res = ressource.objects.get(pk=1)
fields = res._meta.fields # This will return tuple-like object.
for field in fields:
if field.name == 'media':
# you want to find "media" field
print(field.choices) # This will return all available choices on your media field
希望,对您有帮助。祝你好运。