如何使用Django为数据库创建CLI

问题描述 投票:0回答:1

我是一名学生,我被分配到一个项目,我正在使用Django + PostgreSQL,我应该制作一个CLI(命令行界面)可能与Django显示我的数据库模块。最简单的方法是什么?我只对C ++编程有一些了解,所以我在想一个switch语句,用户可以选择不同的查询,但我不知道如何在Django中做到这一点。

谢谢 :)

django postgresql
1个回答
0
投票

如果要访问数据库shell,只需运行./manage.py dbshell。但是如果你想直接从命令行显示你的表,你可以使用custom django management命令,但显示表与Django无关,而不是仅使用python的SQL查询。例如:

你可以在any_django_app/management/commands中添加一个新的python文件,并将其命名为show_tables.py,在其中,输入以下代码:

from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections


class Command(BaseCommand):
    help = (
        "Shows DB tables, also you can pass your DATABASE NAME through this command"
    )

    requires_system_checks = False

    def add_arguments(self, parser):
        parser.add_argument(
            '--database', default=DEFAULT_DB_ALIAS,
            help='Nominates a database onto which to open a shell. Defaults to the "default" database.',
        )

    def handle(self, **options):
        connection = connections[options['database']]
        try:
            cursor = connection.cursor()
            cursor.execute("""SELECT table_name FROM information_schema.tables
                WHERE table_schema = 'public'""")
            for table in cursor.fetchall():
                print(table[0])
        except OSError:
            # Note that we're assuming OSError means that the client program
            # isn't installed. There's a possibility OSError would be raised
            # for some other reason, in which case this error message would be
            # inaccurate. Still, this message catches the common case.
            raise CommandError(
                'You appear not to have the %r program installed or on your path.' %
                connection.client.executable_name
            )

现在,运行./manage.py show_tables,然后它将显示数据库中的表。

© www.soinside.com 2019 - 2024. All rights reserved.