我有一个MySQL列,其中包含以下信息:
codes = [
"[1]",
"[1-1]",
"[1-1-01]",
"[1-1-01-01]",
"[1-1-01-02]",
"[1-1-01-03]",
"[1-1-02]",
"[1-1-02-01]",
"[1-1-02-02]"
"[1-2]",
"[1-2-01]",
"[1-2-01-01]",
"[2]",
"[2-1]",
"[2-1-01-01]",
"[2-1-01-02]"
]
这是帐户的层次结构,对于每个帐户,我都需要知道,哪个帐户是父帐户,哪个帐户是要添加到名为AccountsTree
的辅助表中的子帐户。
我的模特是:
Accounts:
id = db.Column(Integer)
account = db.Column(Integer)
...
numbers = db.Column(Integer)
AccountsTree:
id = db.Column(Integer)
parent = db.Column(Integer, db.ForeignKey('Accounts.id')
child = db.Column(Integer, db.ForeignKey('Accounts.id')
我开始编写类似的代码:
For each_element in code_list:
replace "[" and "]"
split strings in '-' and
make a new list of lists: each list element is a list of codes, each element of the inner list is a level
但这看起来似乎不太好,而且似乎在增加不必要的复杂性。
我的工作流程是:
(1) Import XLS from front end
(2) Parse XLS and add information to Accounts table
(3) Find out hierarchy of accounts and add information to AccountsTree table
我目前正在努力进行第三步。那么,在将信息添加到Accounts表之后,如何找出填充AccountsTree表的层次结构?
我想要的结果是:
ParentID | ChildID
1 | 2
2 | 3
3 | 4
3 | 4
3 | 5
3 | 6
任何人都经历过类似的挑战并且可以分享一种最有效的方法吗? 谢谢