Peewee获得所有后代

Peewee get all descendants

我在 python 中使用 peewee 作为 ORM(与 postgresql 结合),我试图从 table 中查询给定 id 的每个后代自引用 (parent-child)

实现此目标的最佳方法是什么?

编辑:

我已经设置了 peewee 模型 class:

class Customer(BaseModel):
    customerid = PrimaryKeyField()
    name = CharField(null=False)
    parentid = ForeignKeyField(db_column='parentid',
                           null=True,
                           rel_model='self', to_field='customerid')
    customer_type_customertypeid = ForeignKeyField(
        db_column='customer_type_customertypeid',
        null=False,
        rel_model=CustomerType, to_field='customertypeid')

class Meta:
    db_table = 'customer'

现在我想通过 id 查询给定客户的每个 child 并将其转换为字典

C1 = dbhandler.Customer.alias()

try:
    return [model_to_dict(model) for model in
        C1.select().where(...)]
except:
     return {}

但我想不出不使用 CTE 就能实现此目的的查询。但是由于 peewee 不支持 CTE,所以我没有想法。 我确实看到 peewee 有一个 .raw(..) 函数,您可以在其中放置真正的 sql 查询,但这只会破坏使用 ORM 的优势。

您可能想要执行递归通用 table 表达式。 Peewee 2.x 还不支持这个,但它在 3.0 中,目前还没有发布,因为它有很多变化,我还没有完成一些 API。对不起!试图把它弄出来。

无论如何,您可以使用 MyModel.raw('WITH ... ') 来 运行 递归 CTE 并接收模型实例。