Python Peewee 模型到 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21975920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Peewee model to JSON
提问by shoopdelang
I'm creating an API using peewee as the ORM and I need the ability to convert a peewee model object into a JSON object to send to the user. Does anyone know of a good way to do this?
我正在使用 peewee 作为 ORM 创建 API,我需要能够将 peewee 模型对象转换为 JSON 对象以发送给用户。有谁知道这样做的好方法吗?
采纳答案by Ali SAID OMAR
you can do something like that:
你可以这样做:
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
回答by coleifer
Peewee has a model_to_dictand dict_to_modelhelpers in the playhouse.shortcutsextension module.
Peewee在扩展模块中有一个model_to_dict和dict_to_modelhelpers playhouse.shortcuts。
- http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict
- http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#dict_to_model
- http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict
- http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#dict_to_model
You could use these as follows:
您可以按如下方式使用这些:
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))
Also note that model_to_dict()can recurse through related models, include back-referenced models, and exclude certain fields from being serialized.
另请注意,model_to_dict()可以通过相关模型进行递归,包括反向引用模型,并从序列化中排除某些字段。
回答by kiba
also, you can get model as a dict, and then convert to json with correct field types (bool, int, float, etc.):
此外,您可以将模型作为字典,然后使用正确的字段类型(bool、int、float 等)转换为 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)
回答by Ron Reiter
I usually implement the model to dict and dict to model functions, for maximum security and understanding of the inner workings of the code. Peewee does a lot of magic and you want to be in control over it.
我通常将模型实现为 dict 和 dict 为函数建模,以实现最大的安全性和对代码内部工作的理解。Peewee 有很多魔法,你想控制它。
The most obvious argument for why you should not iterate on the fields but rather explicitly specify them is because of security considerations. Not all fields can be exposed to the user, and I assume you need this functionality to implement some sort of REST API.
为什么不应该迭代字段而是明确指定它们的最明显的论点是出于安全考虑。并非所有字段都可以向用户公开,我假设您需要此功能来实现某种 REST API。
So - you should do something like this:
所以 - 你应该做这样的事情:
class UserData(db.Model):
user = db.ForeignKeyField(User)
data = db.CharField()
def serialize():
# front end does not need user ID here
return {
'data': self.data
}
@classmethod
def from_json(cls, json_data):
UserData.create(
# we enforce user to be the current user
user=current_user,
data=json_data['data']
)
回答by Matteo Furlan
I had this very same problem and ended up defining my own parser extension for JSON types that could not be automatically serialized. I'm fine for now in using strings as data represented (although you could possibly use different datatypes, but beware of approximation using floating points!
我遇到了同样的问题,最终为无法自动序列化的 JSON 类型定义了自己的解析器扩展。我现在可以使用字符串作为数据表示(尽管您可能会使用不同的数据类型,但要注意使用浮点的近似值!
In the following example, I put this in a file called json_serialize.pyinside a utilsfolder:
在下面的例子中,我把它放在一个文件夹json_serialize.py内的utils文件中:
from decimal import Decimal
import datetime
try:
import uuid
_use_uuid = True
except ImportError:
_use_uuid = False
datetime_format = "%Y/%m/%d %H:%M:%S"
date_format = "%Y/%m/%d"
time_format = "%H:%M:%S"
def set_datetime_format(fmt_string):
datetime_format = fmt_string
def set_date_format(fmt_string):
date_format = fmt_string
def set_time_format(fmt_string):
time_format = fmt_string
def more(obj):
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, datetime.datetime):
return obj.strftime(datetime_format)
if isinstance(obj, datetime.date):
return obj.strftime(date_format)
if isinstance(obj, datetime.time):
return obj.strftime(time_format)
if _use_uuid and isinstance(obj, uuid.UUID):
return str(obj.db_value())
raise TypeError("%r is not JSON serializable" % obj)
Then, in my app:
然后,在我的应用程序中:
import json
from utils import json_serialize
...
json.dumps(model_to_dict(User.get()), default=json_serialize.more)
edit just to add: this is very largely inspired by json_utils.defaultmodule found in mongodb but mainly relies on the jsonmodule and needs no import of mongodb own bson/json_utils module.
编辑只是添加:这很大程度上受到json_utils.defaultmongodb 中的模块的启发,但主要依赖于该json模块,不需要导入 mongodb 自己的 bson/json_utils 模块。
Usually I update it to support new types as soon as my app raises the TypeErrorfor it found a type not able to serialize
通常我会在我的应用程序启动后立即更新它以支持新类型,因为TypeError它发现了无法序列化的类型
回答by Pramit Sawant
when single fetch
单取时
user = User.select().where(User.id == 1).get()
model_to_dict(user) #to Dict
when Multiple fetch
当多取
users = list(User.select().where(User.name ** 'a%').dicts())

