如何显示烧瓶中数据库中的链接数据? [英] How to display linked data from database in flask?
问题描述
我的数据库中有一个包含链接列表的表。
I have a table in my database containing a linked list.
ID | page | prior | next
1 | A | 0 | 2
2 | B | 1 | 3
3 | C | 2 | 4
4 | D | 3 | 5
5 | E | 4 | 0
如何显示此表中的所有项目?经过几次位置互换和插入操作后, SORT BY
无效。我正在使用Flask,它使用Jinja2模板。我当前的方法是找到第一个项目并将其添加到列表中。然后,根据上一项的下一个值,收集下一行并将其添加到列表中。
How do I display all the items in this table? A SORT BY
wouldn't work after a few positional swaps and insertions. I'm using Flask, which uses Jinja2 templates. My current approach is to locate the first item and add it to a list. Then, based on the previous item's "next" value, collect the next row and add it to the list.
num_rows = Pages.query.count()
# find first row, the one where prior is 0
first_row = Pages.query.filter_by(prior=0).first()
# create a list containing just the first row for now
all_rows = [first_row, ]
# add new rows to the list
for i in range(0, (num_rows-1)):
current_row = all_rows[i].next
all_rows.append(Pages.query.get(current_row))
最后,我将列表传递给 render_template('template.html',all_rows = all_rows)
,然后检索
Finally, I pass the list to render_template('template.html', all_rows = all_rows)
, then retrieve it in the template.
肯定有一种更优雅的方法吗?我想这会执行得很糟糕并且需要大量资源吗?
Surely there's a more elegant approach? I imagine that this would perform terribly and require lots of resources?
推荐答案
这取决于您使用的是哪种DBMS。 Oracle具有专有的按优先级连接
语法,该语法非常易于阅读。许多其他语言的 WITH
语法较难理解,但可以实现相同的结果。
It depends on what DBMS you’re using. Oracle has a proprietary CONNECT BY PRIOR
syntax that’s very easy to read. Many others have a WITH
syntax that’s harder to follow but can accomplish the same result.
请参见在SQL SERVER中模拟ORACLE的PRI优先级连接。
这篇关于如何显示烧瓶中数据库中的链接数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!