首页 > 数据库 >django 数据库model取值转为字典(或json)

django 数据库model取值转为字典(或json)

时间:2022-10-19 12:13:36浏览次数:65  
标签:info list prj json dict env model django

​方法一,使用model_to_dict

from django.forms.models import model_to_dict
​
list = ProjectCase.objects.filter(prj_id=prj_id).order_by('-prc_id')
​
 data = []           
 for info in list:
    json_dict = model_to_dict(prc_info)
    data.append(json_dict)

方法二,循环取值,可自定义字段

prj_list = Project.objects.all().order_by('-prj_id')
data = []
for prj_info in prj_list:
    json_dict = {}
    json_dict['prj_id'] = prj_info.prj_id
    json_dict['prj_name'] = prj_info.prj_name
    
    data.append(json_dict)

方法三,序列化,但是序列化后data参数在结果的fields里面,还要再处理

from django.core import serializers
env_list = Env.objects.all()
    env_list = serializers.serialize('json', env_list)
    env_list = json.loads(env_list)
    data = []
    for env_info in env_list:
        env_name = env_info['fields']['env_name']
        hostname = env_info['fields']['hostname']
​
        info = {"value": hostname, "label": env_name, }
        data.append(info)

 

标签:info,list,prj,json,dict,env,model,django
From: https://www.cnblogs.com/sugoi/p/16805818.html

相关文章