Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peewee model to JSON

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?

like image 606
shoopdelang Avatar asked Feb 23 '14 23:02

shoopdelang


3 Answers

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.

like image 115
coleifer Avatar answered Nov 01 '22 04:11

coleifer


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()) 
like image 44
Pramit Sawant Avatar answered Nov 01 '22 06:11

Pramit Sawant


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)
like image 4
kiba Avatar answered Nov 01 '22 06:11

kiba