I have a problem with Peewee-3 and one of the tutorials in documentation: http://docs.peewee-orm.com/en/latest/peewee/querying.html#recursive-ctes
When I’m trying to run this code (nearly exact copy from doc) it’s rising an error:
Exception has occurred: OperationalError no such column: base.id
Here is my code (there is commented part with some testing categories):
JavaScript
x
57
57
1
_db = SqliteDatabase(DB_FILE)
2
3
class _Base(Model):
4
class Meta:
5
database = _db
6
7
class Category(_Base):
8
name = CharField()
9
parent = ForeignKeyField('self', backref='children', null=True)
10
11
12
# ADDING CATEGORIES
13
# _db.connect()
14
# _db.create_tables([Category])
15
# stocks = Category(name="stocks", parent=None)
16
# stocks.save()
17
# models = Category(name="models", parent=None)
18
# models.save()
19
20
# smoke = Category(name="smoke", parent=stocks)
21
# smoke.save()
22
23
# front = Category(name="front", parent=smoke)
24
# front.save()
25
26
# side = Category(name="side", parent=smoke)
27
# side.save()
28
29
# fluffy = Category(name="fluffy", parent=front)
30
# fluffy.save()
31
# _db.close()
32
33
34
Base = Category.alias()
35
level = Value(1).alias('level')
36
path = Base.name.alias('path')
37
base_case = (Base
38
.select(Base.name, Base.parent, level, path)
39
.where(Base.parent.is_null())
40
.cte('base', recursive=True))
41
42
RTerm = Category.alias()
43
rlevel = (base_case.c.level + 1).alias('level')
44
rpath = base_case.c.path.concat('->').concat(RTerm.name).alias('path')
45
recursive = (RTerm
46
.select(RTerm.name, RTerm.parent, rlevel, rpath)
47
.join(base_case, on=(RTerm.parent == base_case.c.id)))
48
49
cte = base_case.union_all(recursive)
50
51
query = (cte
52
.select_from(cte.c.name, cte.c.level, cte.c.path)
53
.order_by(cte.c.path))
54
55
for category in query:
56
print(category.name, category.level, category.path)
57
What am I doing wrong and how can I fix it, there is an mistake in the documentation?
Advertisement
Answer
Thanks for the issue report. The problem is I omitted to select the category “id” in the example from the docs. The fix is quite simple:
JavaScript
1
10
10
1
base_case = (Base
2
.select(Base.id, Base.name, Base.parent, level, path) # Add Base.id
3
.where(Base.parent.is_null())
4
.cte('base', recursive=True))
5
6
7
recursive = (RTerm
8
.select(RTerm.id, RTerm.name, RTerm.parent, rlevel, rpath) # Add RTerm.id
9
.join(base_case, on=(RTerm.parent == base_case.c.id)))
10
I’ve updated the docs accordingly.