关于Django model 与json序列的转换
2014-03-21 14:57
274 查看
报错
参考如下
http://www.yihaomen.com/article/python/279.htm#2189048-tsina-1-4101-9798c04a6d88069852106b36090cb63b://
在模型类中加入如下代码 将model转换为json
使用时将json序列转成model
MyUser is not JSON serializable
参考如下http://www.yihaomen.com/article/python/279.htm#2189048-tsina-1-4101-9798c04a6d88069852106b36090cb63b://
在模型类中加入如下代码 将model转换为json
class MyUser(models.Model): def toJSON(self): fields = [] for field in self._meta.fields: fields.append(field.name) d = {} import datetime for attr in fields: if isinstance(getattr(self, attr),datetime.datetime): d[attr] = getattr(self, attr).strftime('%Y-%m-%d %H:%M:%S') elif isinstance(getattr(self, attr),datetime.date): d[attr] = getattr(self, attr).strftime('%Y-%m-%d') else: d[attr] = getattr(self, attr) import json return json.dumps(d)
使用时将json序列转成model
def text(request): if 'user' in request.session: user = request.session['user'] user = MyUser(**json.loads(user)) #将json序列转换成model event = UserEvent(user=user,ETime=date.today()) event.save() else: user = None return render_to_response('welcome.html',{'user':user})
相关文章推荐
- django 将model转换成想要都json格式
- 关于在不用Newtonsoft.Json转换的情况下快速给SqlCommand上参数的问题(Model转参数)
- 关于django model postgres的json字段编码问题
- Model实体与Json互相转换
- tornado with MySQL, torndb, django model, SQLAlchemy ==> JSON dumped
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析]
- IOS JSON转换模型库:YYMODEL
- django关于model查询
- 模型转换工具Mantle, MJExtension, JSONModel的使用和异同
- golang关于json库的一个比较容易陷入的坑 uint8[]数组的json转换问题.
- 关于json与java对象转换插件问题
- .net 关于JSON转换为对象时出现的:数据协定类型 “***”无法反序列化,因为未找到必需的数据成员 **(字段名)
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析]
- 关于json与javaBean之间的转换
- 关于JSon中 eval() 把json 的字符串 转换成 对象
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析]
- iOS Json转换模型库:YYModel
- 关于解决对象空值转换成JSON丢失字段的问题
- 关于django model_set 的惨痛教训
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析]