Peewee model to JSON

shoopdelang picture shoopdelang · Feb 24, 2014 · Viewed 27.7k times · Source

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?

Answer

coleifer picture coleifer · Feb 24, 2014

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.