简体   繁体   中英

Convert a Django Model Field Choices into a JSON

I need to convert a model choices tuple, like this one from the Django docs:

YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
)

Into a JSON object like this:

[{"id": 'FR', "year": 'Freshman'}, 
 {"id": 'SO', "year": 'Sophomore'},
 {"id": 'JR', "year": 'Junior'},
 {"id": 'SR', "year": 'Senior'}]

It's a pretty straightforward conversion, and very common when using forms, but i couldnt find any automatic function in Django that works out-the-box. I think I'm missing something here.

In order to get it in the format you want, you would have to do list comprehension:

[{'id': year[0], 'year': year[1]} for year in YEAR_IN_SCHOOL_CHOICES]

you could alternatively use dict(YEAR_IN_SCHOOL_CHOICES) as a " built-in " way to do it, but it would yield:

{'SR': 'Senior', 'FR': 'Freshman', 'SO': 'Sophomore', 'JR': 'Junior'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM