Convert Django model field selection to JSON

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

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

Into a JSON object, for example:

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

This is a fairly simple conversion and is very often used when using forms, but I could not find any automatic function in Django that works out of the box. I think something is missing here.

+4
source share
1 answer

To get it in the format you need, you will need to do the following:

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

you can use dict(YEAR_IN_SCHOOL_CHOICES)as a β€œbuilt-in” way to do this, but it will give:

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

All Articles