Search code examples
pythonjsonpeewee

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?


Solution

  • 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