Gabriel Dintrans
Gabriel Dintrans

Reputation: 113

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.

Upvotes: 5

Views: 2481

Answers (1)

northsideknight
northsideknight

Reputation: 1557

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'}

Upvotes: 6

Related Questions