Peewee model to JSON

老子叫甜甜 提交于 2019-11-30 00:06:28

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
coleifer

Peewee has a model_to_dict and dict_to_model helpers in the playhouse.shortcuts extension module.

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.

also, you can get model as a dict, and then convert to json with correct field types (bool, int, float, etc.):

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)

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.

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.

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']
        )
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!