model 转JSON字符串
class MyUser(models.Model):
ID=....
Name=...
Login=...
Phone=...
Age=....
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)
1、【全】JSON字符串转 model
user = MyUser(**json.loads(user)) #将json序列转换成model
2、【部分】JSON字符串转 model
str = "{\"ID\": \"af1a5de2-58d7-11e8-bf79-e470b883cc29\", \"Login\": \"test001\", \"Name\": \"test001\", \"Pwd\": \"123456\"}"
user = MyUser(**json.loads(str)) #将json序列转换成model
注:JSON串中必须用 " 转义字符,用 ' 会报错
网友评论