Search code examples
pythonpeewee

peewee: classname_set to json array


I'm trying to get the following json with Python peewee.

{'id': 1, 'name': 'John', 'tweet_set': [{'id': 1, 'message': 'hello'},
                                        {'id': 2, 'message': 'world'}]}

But all I can figured out was this:

{'id': 1, 'message': 'hello', 'user': {'id': 1, 'name': 'John'}}
{'id': 2, 'message': 'world', 'user': {'id': 1, 'name': 'John'}}

Here is my code. Where / What can I change to get array of tweets?

from peewee import *
from playhouse.shortcuts import model_to_dict, dict_to_model

db = SqliteDatabase('/tmp/a.db')

class BaseModel(Model):
    class Meta:
        database = db

class User(BaseModel):
    id = PrimaryKeyField()
    name = CharField()

class Tweet(BaseModel):
    id = PrimaryKeyField()
    message = CharField()
    user = ForeignKeyField(User)

db.connect()
db.create_tables([User, Tweet])
db.close()


user_id = User.create(name="John")
Tweet.create(message="hello", user=user_id)
Tweet.create(message="world", user=user_id)

u = User.get(User.name == 'John')

for t in u.tweet_set:
    print(model_to_dict(t))

Solution

  • Try:

    print(model_to_dict(u, backrefs=True))
    

    See documentation, which contains examples: http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict