Peewee model to JSON

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.


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())