繁体   English   中英

列出外部脚本中的Django数据库表名称

[英]List Django database table names from external script

我正在尝试从不属于项目的外部脚本访问Django项目中拥有的sqlite3数据库。

但是,以下内容将返回一个空列表:

con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())

即使我已经将一些模型保存到数据库中。 要检查表名,我在Django shell中使用以下命令:

>>> tables = connection.introspection.table_names()
>>> seen_models = connection.introspection.installed_models(tables)
>>> seen_models
{<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>}
>>> tables
['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete']

我没有在模型的Meta中明确指定表名,所以我猜这些表名是appname_modelnameexplorer_api_activityexplorer_api_athlete )。

但是为什么要空列表?

来自对以下问题的评论:是的,只要您具有文件的有效路径,就可以运行此脚本。 我已经用较小的更改重写了您的脚本,如下所示:

import sqlite3
import os.path

try:
    file_name = raw_input("Enter File Path? ")
except:
    file_name = input("Enter File Path? ")
if os.path.isfile(file_name):
    con = sqlite3.connect(file_name)
    cursor = con.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    print(cursor.fetchall())
else:
    print("File does not exist")

用法:

> python sqlite_tables.py
  (prompt)> Enter File Path? random/file/path
  (prompt)> File does not exist

> python sqlite_tables.py
  (prompt)> Enter File Path? /valid/path/to/database.db
  (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

> python sqlite_tables.py
  (prompt)> Enter File Path? ../database.db  # relative path
  (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM