问题描述:

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?

网友答案:

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
网友答案:

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

  • 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.

网友答案:

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)
相关阅读:
Top