peewee:classname_set 到 json 数组

peewee: classname_set to json array

我正在尝试使用 Python peewee 获得以下 json。

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

但我能想到的是:

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

这是我的代码。我可以在哪里/更改什么来获取推文数组?

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

尝试:

print(model_to_dict(u, backrefs=True))

查看文档,其中包含示例:http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict