2014-02-23 103 views
15

我使用peewee作爲ORM創建API,我需要將peewee模型對象轉換爲JSON對象以發送給用戶的功能。有誰知道這樣做的好方法嗎?Peewee model to JSON

+1

請考慮更改最佳答案。看看票... – coleifer

回答

1

你可以做這樣的事情:

class MyModel(peewee.Model): 

    def __str__(self): 
    r = {} 
    for k in self._data.keys(): 
     try: 
     r[k] = str(getattr(self, k)) 
     except: 
     r[k] = json.dumps(getattr(self, k)) 
    return str(r) 


class User(MyModel): 
    email = CharField() 
    status = CharField(default="enabled") 
    firstname = CharField() 
    lastname = CharField() 
    class Meta: 
     database = db 
+0

記得做'json.dumps(str(user))'而不是'json.dumps(user)' –

+20

這實際上不是一個很好的方法來完成這個。我強烈建議檢查Peewee的'model_to_dict()'helper,它是專門爲此設計的。你可以在這裏找到文檔(http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict)。它也有能夠緩解或排除領域的好處。 – coleifer

+2

爲什麼這是推薦的答案? StackOverflow失敗。 – coleifer

43

Peewee在playhouse.shortcuts擴展模塊中有model_to_dictdict_to_model助手。

如下,您可以用這些:

from playhouse.shortcuts import model_to_dict, dict_to_model 

user_obj = User.select().where(User.username == 'charlie').get() 
json_data = json.dumps(model_to_dict(user_obj)) 

還要注意的是model_to_dict()可以通過相關的模型遞歸,包括背參考模型,並排除某些字段被序列化。

+1

@coleifar!如何導入'model_to_dict()'? – Zaaferani

+1

'from playhouse.shortcuts import *' –

+3

'from playhouse.shortcuts import model_to_dict,dict_to_model' – Arel

3

也,你可以得到的模型作爲一個字典,然後轉換與正確的字段類型(布爾,整數,浮點等),以JSON:

import peewee 
import json 
from bson import json_util 
from datetime import datetime 

class User(peewee.Model): 
    email = CharField() 
    status = BooleanField(default=True) 
    firstname = CharField() 
    lastname = CharField() 
    age = IntegerField() 
    created = DateTimeField(default=datetime.now()) 
    class Meta: 
     database = db 

user = User.select().dicts().get() 
print json.dumps(user, default=json_util.default) 
+0

如果用戶模型具有'created = DateTimeField()',那麼json.dumps(用戶)會抱怨datetime.datetime實例不是JSON可序列化的。在這種情況下,我可以用datetime字段做什麼? –

+1

@Roland試試從[這個答案](http://stackoverflow.com/a/11875813/1270607)解決方案: 'from bson import json_util' 'print json.dumps(user,default = json_util.default)' – kiba

+0

問題是我沒有使用mongodb。儘管嘗試使用python builtin bson,我得到了類似「{」born「:{」$ date「:1399579518000},」name「:」John Smith「}''的東西。並試圖使用這個:https://pypi.python.org/pypi/bson/0.3.3崩潰的應用程序。謝謝你的提示。 –