Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将Django模型字段选项转换为JSON_Python_Json_Forms_Django Models - Fatal编程技术网

Python 将Django模型字段选项转换为JSON

Python 将Django模型字段选项转换为JSON,python,json,forms,django-models,Python,Json,Forms,Django Models,我需要转换一个模型选择元组,就像Django文档中的这个: YEAR_IN_SCHOOL_CHOICES = ( ('FR', 'Freshman'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ) 进入JSON对象,如下所示: [{"id": 'FR', "year": 'Freshman'}, {"id": 'SO', "year": 'Sophomore'}, {"id": 'JR', "year": 'Jun

我需要转换一个模型选择元组,就像Django文档中的这个:

YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
)
进入JSON对象,如下所示:

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

这是一个非常简单的转换,在使用表单时非常常见,但是我在Django中找不到任何自动的函数来解决这个问题。我想我在这里遗漏了一些东西。

为了获得您想要的格式,您必须执行列表理解:

[{'id': year[0], 'year': year[1]} for year in YEAR_IN_SCHOOL_CHOICES]
您也可以使用
dict(在学年份的选择)
作为一种“内置”方式,但它会产生:

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