Python 使用Peewee或其他ORM的一种方法在数据库中保存嵌套对象

Python 使用Peewee或其他ORM的一种方法在数据库中保存嵌套对象,python,mysql,orm,peewee,Python,Mysql,Orm,Peewee,假设我有这样的模型: class user(Model): rep = ForeignKeyField('reputation') class reputation(Model): metrics = ForeignKeyField('metric') class metric(Model): rate = IntegerField() stars = IntegerField() comments = IntegerField() 使用playhouse模块

假设我有这样的模型:

class user(Model):
   rep = ForeignKeyField('reputation')

class reputation(Model):
   metrics = ForeignKeyField('metric')

class metric(Model):
   rate = IntegerField()
   stars = IntegerField()
   comments = IntegerField()
使用playhouse模块快捷方式,我可以将整个dict转换为用户对象dict-to-U模型。此主对象包含嵌套的对象,这些对象已包含我需要的所有信息。我正在寻找一种ORM方法来简化我将这个用户保存到数据库的方式。例如:user.create\u all\u recursive()。我已经搜索过了,但在peewee文档中没有找到任何东西


这只是一个示例,但目前我有一个模型,其中包含23个嵌套对象,这些对象是从唯一的API接收的。我在寻找某种方法或技巧,从嵌套行开始,按顺序在数据库中创建所有行。在我的示例中,如果我尝试使用peewee保存user.create(),我将收到一个错误,通知没有相应的度量来连接。

签出
ModelClass.\u meta.model\u graph
,它遍历模型引用和反向引用的图形。如果要从“根”模型到所有依赖项,则需要搜索回引用,如下所示:

from peewee import *

class A(Model): pass
class B(Model):
    a = ForeignKeyField(A)
class C(Model):
    b = ForeignKeyField(B)
    c = ForeignKeyField('self', null=True)
class D(Model):
    b = ForeignKeyField(B)

A._meta.model_graph(refs=False)                                                        
# returns:
[(None, <Model: A>, None),
 (<ForeignKeyField: B.a>, <Model: B>, True),
 (<ForeignKeyField: C.b>, <Model: C>, True),
 (<ForeignKeyField: D.b>, <Model: D>, True),
 (<ForeignKeyField: C.c>, <Model: C>, True)]
来自peewee导入的
*
甲级(模型):合格
B类(型号):
a=外键字段(a)
丙类(型号):
b=外键字段(b)
c=ForeignKeyField('self',null=True)
D类(型号):
b=外键字段(b)
A.。_元模型_图(参考值=假)
#返回:
[(没有,没有),
(,没错),
(,没错),
(,没错),
(,对)]
您可能希望以相反的顺序进行迭代