如何在Sqlite数据库中表示嵌套文件夹和子文件夹结构?

2024-06-28 10:59:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python表示Sqlite数据库中的一个文件夹结构,其中每个表的行为就像它自己的文件夹一样,可以是另一个表的父、子或同级。在

我当前的设置将它们嵌套在分隔符中,如下所示:

  • ['folder::subfoldera']
  • ['folder::subfolderb']
  • ['folder2::subfolderc']
  • ['folder2::subfolderd']
  • ['last::example::to::representation::depth']

但是,我不知道如何在数据库中嵌套,因为我不知道如何在这个文件夹中嵌套。在

我应该如何处理a)在数据库中存储表b)用Python表示它们的结构?在


Tags: to文件夹数据库sqliteexamplefolder结构last
1条回答
网友
1楼 · 发布于 2024-06-28 10:59:38

最好将文件夹结构存储在一个表中,而不是为每个文件夹创建一个表。在

例如,这样的表可以具有如下结构:

╔═══════════╦══════╦══════════════════════════════════╗
║  Column   ║ Type ║           Description            ║
╠═══════════╬══════╬══════════════════════════════════╣
║ id        ║ int  ║ Unique identifier of the folder  ║
║ parent_id ║ int  ║ id of the parent folder          ║
║ name      ║ text ║ Name of the folder               ║
║ mpath     ║ text ║ Materialized path of parent id's ║
╚═══════════╩══════╩══════════════════════════════════╝

关于具体化路径的注意事项:它是可选的,可以添加它来更快地运行查询,比如“getallchildoffolder123”,而不需要重复调用。在

假设你有这样的文件夹结构:

^{pr2}$

可以如下表的形式表示:

╔════╦═══════════╦═══════════════════╦═══════════╗
║ id ║ parent_id ║       name        ║   mpath   ║
╠════╬═══════════╬═══════════════════╬═══════════╣
║  1 ║ null      ║ "/"               ║ "/"       ║
║  2 ║ 1         ║ "home"            ║ "/1/"     ║
║  3 ║ 2         ║ "aspiring-master" ║ "/1/2/"   ║
║  4 ║ 3         ║ ".bashrc"         ║ "/1/2/3/" ║
║  5 ║ 2         ║ "guest-user"      ║ "/1/2/"   ║
║  6 ║ 1         ║ "var"             ║ "/1/"     ║
║  7 ║ 6         ║ "log"             ║ "/1/6/"   ║
║  8 ║ 6         ║ "lib"             ║ "/1/6/"   ║
╚════╩═══════════╩═══════════════════╩═══════════╝

在python中,您可以使用一些ORM,例如sqlAlchemy,在这种情况下,您的文件夹将被表示为一个类,实现模型:

^{4}$

自动创建mpath值的功能也可以放在这个类中。在

相关问题 更多 >