有没有办法在Django视图中显示数据库的信息?
例如,我知道在Heroku cli中你可以heroku pg:info -a your_app
查看数据库的表计数,行数,类型等。
有没有办法在Django中获取相同的信息,使其在模板中可以查看以跟踪存储等?
答案 0 :(得分:0)
我使用以下函数来获取当前数据库的行数:
from django.db import connections
def db_row_count():
cursor = connections['default'].cursor()
query = """
SELECT sum(reltuples)
FROM pg_class
WHERE relname
IN (
SELECT c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n
ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
);
"""
cursor.execute(query)
row = cursor.fetchone()
return int(row[0])