需求一,将数据对象转为dict,但是不包括relation,
import BaseClass #所有模型的基础类 def getDictFromObj_nr(obj): return_dict={} if isinstance(obj,BaseClass): for key in obj.__dict__ : if key.startswith('_'):continue return_dict[key]=getattr(obj,key) return return_dict
需求二,将数据对象转为dict,但是包括relation,凡是定义了relation的,就会提出relation对应的对象,或者对象列表。
import BaseClass import getDictFromObj_nr
def getDictFromObj(self,obj): ''' 包括relation,对象转dict :param obj: :return: ''' return_dict={} if isinstance(obj,BaseClass): for key in [x for x in dir(obj) if not x.startswith('_') and x not in ["get", "iteritems", "metadata", "next", "save", "update"]]: value=getattr(obj,key) if isinstance(value,list): return_dict[key]=[] for item in value: if isinstance(item,BaseClass): return_dict[key].append(getDictFromObj_nr(item)) else: return_dict[key].append(item) elif isinstance(value,BaseClass): return_dict[key]=getDictFromObj_nr(value) else: return_dict[key]=getattr(obj,key) return return_dict else: return obj