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

时间:2018-11-14 12:48:25

标签: django postgresql

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

谢谢:)

1 个答案:

答案 0 :(得分:0)

如果要访问数据库外壳,只需运行./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,然后它将显示数据库中的表。