1. 程式人生 > >python學習-- Django進階之路 model的 objects對象 轉 json

python學習-- Django進階之路 model的 objects對象 轉 json

amp nbsp urn ext iterable code port django item

# objects_to_json: 將 model對象 轉化成 json
# json_to_objects: 將 將反序列化的json 轉為 model 對象

def json_field(field_data):

"""
將字典的鍵值轉化為對象
:param field_data:
:return:
"""
if isinstance(field_data, str):
return "\"" + field_data + "\""
elif isinstance(field_data, bool):
if field_data == ‘False‘:

return ‘false‘
else:
return ‘true‘
elif isinstance(field_data, unicode):
return "\"" + field_data.encode(‘utf-8‘) + "\""
elif field_data is None:
return "\"\""
else:
return "\"" + str(field_data) + "\""


def json_encode_dict(dict_data):
"""

將字典轉化為json序列
:param dict_data:
:return:
"""
json_data = "{"
for (k, v) in dict_data.items():
json_data = json_data + json_field(k) + ‘:‘ + json_field(v) + ‘, ‘
json_data = json_data[:-2] + "}"
return json_data


def json_encode_list(list_data):

"""
將列表中的字典元素轉化為對象

:param list_data:
:return:
"""
json_res = "["
for item in list_data:
json_res = json_res + json_encode_dict(item) + ", "
return json_res[:-2] + "]"


def objects_to_json(objects, model):

"""
將 model對象 轉化成 json
example:
1. objects_to_json(Test.objects.get(test_id=1), EviewsUser)
2. objects_to_json(Test.objects.all(), EviewsUser)
:param objects: 已經調用all 或者 get 方法的對象
:param model: objects的 數據庫模型類
:return:
"""
from collections import Iterable
concrete_model = model._meta.concrete_model
list_data = []

# 處理不可叠代的 get 方法
if not isinstance(object, Iterable):
objects = [objects, ]

for obj in objects:
dict_data = {}
print concrete_model._meta.local_fields
for field in concrete_model._meta.local_fields:
if field.name == ‘user_id‘:
continue
value = field.value_from_object(obj)
dict_data[field.name] = value
list_data.append(dict_data)

data = json_encode_list(list_data)
return data


def json_to_objects(json_str, model):

"""
將 將反序列化的json 轉為 model 對象
example:
Test model 預先定義
test_str = ‘[{"test_id":"0", "test_text":"hello json_to_objects"}]‘
json_to_objects(json_str, model)
:param json_str:
:param model: objects的 數據庫模型類
:return:
"""
import ast
json_list = ast.literal_eval(json_str)
obj_list = []
field_key_list = [field.name for field in model._meta.concrete_model._meta.local_fields]
for item in json_list:
obj = model()
for field in item:
if field not in field_key_list:
raise ValueError(‘數據庫無 ‘ + field + ‘ 字段‘)
setattr(obj, field, item[field])
obj_list.append(obj)
return obj_list

python學習-- Django進階之路 model的 objects對象 轉 json