I'm trying to use the recursive CTE from Peewee ORM that returns the same field types as a non-recursive query.
According to the Peewee docs, you use the select_from
method, with columns from the previous query, like this:
query = (cte
.select_from(cte.c.name, cte.c.level, cte.c.path)
.order_by(cte.c.path))
My query basically works. However, my table uses a couple of custom field types. When using regular query those fields are converted by the field to objects as defined in the python_value
method. But when using the CTE query those values come as the raw database type, not converted by the custom field method.
Is there a way to tell the query to use the field conversion?
I tried .select_from(cte.c.myfield.convert(MyEnum), ...)
, but that doesn't work.
The select_from()
method returns you a "bare" Select query that does not know so much about converting values. This should work:
from peewee import ModelSelect
class Reg(Model):
value = TextField()
Reg.create(value='1')
Reg.create(value='22')
cte = Reg.select(Reg.value).cte('regs', columns=('val',))
query = ModelSelect(Reg, (cte.c.val.converter(int),))
query = query.from_(cte).with_cte(cte)
for row in query:
print(type(row.val), row.val)
# <class 'int'> 1
# <class 'int'> 22