your programing

Django에서 manage.py CLI를 사용하여 데이터베이스에서 모든 테이블을 삭제하는 방법은 무엇입니까?

lovepro 2020. 10. 6. 18:52
반응형

Django에서 manage.py CLI를 사용하여 데이터베이스에서 모든 테이블을 삭제하는 방법은 무엇입니까?


manage.py 및 명령 줄을 사용하여 데이터베이스에서 모든 테이블을 삭제하려면 어떻게해야합니까? .NET 응용 프로그램에서 실행할 수 있도록 적절한 매개 변수로 manage.py를 실행하는 방법이 있습니까?


내가 아는 한 모든 테이블을 삭제하는 관리 명령은 없습니다. Python을 해킹해도 괜찮다면 사용자 지정 명령을 작성하여 수행 할 수 있습니다. sqlclear흥미로운 옵션을 찾을 수 있습니다 . 문서에 따르면 ./manage.py sqlclear 주어진 앱 이름에 대한 DROP TABLE SQL 문을 인쇄합니다.

업데이트 : 이 답변 아래에 @Mike DeSimone 의 의견을 뻔뻔 스럽게 적용 하여 완전한 답변을 제공합니다.

./manage.py sqlclear | ./manage.py dbshell

django 1.9 현재입니다. ./manage.py sqlflush


South 패키지를 사용하여 데이터베이스 마이그레이션을 처리하는 경우 (적극 권장) ./manage.py migrate appname zero명령 만 사용할 수 있습니다 .

그렇지 않으면 ./manage.py dbshell표준 입력에서 SQL 명령을 파이핑 하는 명령을 권장합니다 .


모든 테이블을 삭제하는 기본 Django 관리 명령은 없습니다. 둘 다 sqlclearreset앱 이름이 필요합니다.

그러나 원하는 것을 정확히 수행하는 (그리고 더 많은 유용한 관리 명령에 대한 액세스를 제공 하는) 제공하는 Django Extensions설치할 수 있습니다 .manage.py reset_db


python manage.py migrate <app> zero

sqlclear 1.9에서 제거되었습니다.

릴리스 노트에는 마이그레이션 도입 때문이라고 언급되어 있습니다. https://docs.djangoproject.com/en/1.9/releases/1.9/

안타깝게도 한 번에 모든 앱에서 작동하는 방법을 찾을 수 없었고 관리자로부터 설치된 모든 앱을 나열하는 기본 제공 방법도 찾을 수 없었 습니다. Django에서 manage.py를 사용하여 설치된 모든 앱을 나열하는 방법은 무엇입니까?

관련 : Django 1.7에서 마이그레이션을 재설정하는 방법?


./manage.py sqlflush | ./manage.py dbshellsqlclear 를 사용 하려면 앱을 플러시해야하므로 사용하는 것이 좋습니다 .


파이썬에서 간단한 (?) 방법 (mysql에서) :

from django.db import connection

cursor = connection.cursor()
cursor.execute('show tables;')
parts = ('DROP TABLE IF EXISTS %s;' % table for (table,) in cursor.fetchall())
sql = 'SET FOREIGN_KEY_CHECKS = 0;\n' + '\n'.join(parts) + 'SET FOREIGN_KEY_CHECKS = 1;\n'
connection.cursor().execute(sql)

다음은이 문제를 처리하기 위해 함께 연결 한 쉘 스크립트입니다. 누군가 시간을 절약하기를 바랍니다.

#!/bin/sh

drop() {
    echo "Droping all tables prefixed with $1_."
    echo
    echo "show tables" | ./manage.py dbshell |
    egrep "^$1_" | xargs -I "@@" echo "DROP TABLE @@;" |
    ./manage.py dbshell
    echo "Tables dropped."
    echo
}

cancel() {
    echo "Cancelling Table Drop."
    echo
}

if [ -z "$1" ]; then
    echo "Please specify a table prefix to drop."
else
    echo "Drop all tables with $1_ prefix?"
    select choice in drop cancel;do
        $choice $1
        break
    done
fi

데이터베이스를 완전히 지우고 동시에 다시 동기화하려면 다음과 같은 것이 필요합니다. 또한이 명령에 테스트 데이터 추가를 결합합니다.

#!/usr/bin/env python

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") # Replace with your app name.

from django.db import connection
from django.core.management import call_command
from django.conf import settings
# If you're using postgres you can't use django's sql stuff for some reason that I
# can't remember. It has to do with that autocommit thing I think.
# import psychodb2 as db

def recreateDb():
    print("Wiping database")
    dbinfo = settings.DATABASES['default']

    # Postgres version
    #conn = db.connect(host=dbinfo['HOST'], user=dbinfo['USER'],
    #                 password=dbinfo['PASSWORD'], port=int(dbinfo['PORT'] or 5432))
    #conn.autocommit = True
    #cursor = conn.cursor()
    #cursor.execute("DROP DATABASE " + dbinfo['NAME'])
    #cursor.execute("CREATE DATABASE " + dbinfo['NAME'] + " WITH ENCODING 'UTF8'") # Default is UTF8, but can be changed so lets be sure.

    # Mysql version:
    print("Dropping and creating database " + dbinfo['NAME'])
    cursor = connection.cursor()
    cursor.execute("DROP DATABASE " + dbinfo["NAME"] + "; CREATE DATABASE " + dbinfo["NAME"] + "; USE " + dbinfo["NAME"] + ";")
    print("Done")


if __name__ == "__main__":
    recreateDb();
    print("Syncing DB")
    call_command('syncdb', interactive=False)
    print("Adding test data")
    addTestData() # ...

It would be nice to be able to do cursor.execute(call_command('sqlclear', 'main')) but call_command prints the SQL to stdout rather than returning it as a string, and I can't work out the sql_delete code...


Using Python to make a flushproject command, you use :

from django.db import connection
cursor = connection.cursor()
cursor.execute(“DROP DATABASE %s;”, [connection.settings_dict['NAME']])
cursor.execute(“CREATE DATABASE %s;”, [connection.settings_dict['NAME']])

The command ./manage.py sqlclear or ./manage.py sqlflush seems to clear the table and not delete them, however if you want to delete the complete database try this : manage.py flush.

Warning: this will delete your database completely and you will lose all your data, so if that not important go ahead and try it.


This answer is for postgresql DB:

Run: echo 'drop owned by some_user' | ./manage.py dbshell

NOTE: some_user is the name of the user you use to access the database, see settings.py file:

default_database = {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'somedbname',
    'USER': 'some_user',
    'PASSWORD': 'somepass',
    'HOST': 'postgresql',
    'PORT': '',
}

Here's a south migration version of @peter-g's answer. I often fiddle with raw sql, so this comes in handy as 0001_initial.py for any befuddled apps. It will only work on DBs that support SHOW TABLES (like mysql). Substitute something like SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'; if you use PostgreSQL. Also, I often do this exact same thing for both the forwards and backwards migrations.

from south.db import db
from south.v2 import SchemaMigration
from django.db.utils import DatabaseError
from os import path
from logging import getLogger
logger = getLogger(__name__)


class Migration(SchemaMigration):

    def forwards(self, orm):

        app_name = path.basename(path.split(path.split(path.abspath(__file__))[0])[0])
        table_tuples = db.execute(r"SHOW TABLES;")

        for tt in table_tuples:
            table = tt[0]
            if not table.startswith(app_name + '_'):
                continue
            try:
                logger.warn('Deleting db table %s ...' % table)
                db.delete_table(table)
            except DatabaseError:
                from traceback import format_exc
                logger.error("Error running %s: \n %s" % (repr(self.forwards), format_exc()))

Coworker/cocoders would kill me if they knew I did this, though.


There's an even simpler answer if you want to delete ALL your tables. You just go to your folder containing the database (which may be called mydatabase.db) and right-click the .db file and push "delete." Old fashioned way, sure-fire to work.


Drops all tables and recreates them:

python manage.py sqlclear app1 app2 appN | sed -n "2,$p" | sed -n "$ !p" | sed "s/";/" CASCADE;/" | sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/" | python manage.py dbshell
python manage.py syncdb

Explanation:

manage.py sqlclear - "prints the DROP TABLE SQL statements for the given app name(s)"

sed -n "2,$p" - grabs all lines except first line

sed -n "$ !p" - grabs all lines except last line

sed "s/";/" CASCADE;/" - replaces all semicolons (;) with (CASCADE;)

sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/" - inserts (BEGIN;) as first text, inserts (COMMIT;) as last text

manage.py dbshell - "Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER, PASSWORD, etc., settings"

manage.py syncdb - "Creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created"

Dependencies:


Credits:

@Manoj Govindan and @Mike DeSimone for sqlclear piped to dbshell

@jpic for 'sed "s/";/" CASCADE;/"'


Here's an example Makefile to do some nice things with multiple settings files:

test:
    python manage.py test --settings=my_project.test

db_drop:
    echo 'DROP DATABASE my_project_development;' | ./manage.py dbshell
    echo 'DROP DATABASE my_project_test;' | ./manage.py dbshell

db_create:
    echo 'CREATE DATABASE my_project_development;' | ./manage.py dbshell
    echo 'CREATE DATABASE my_project_test;' | ./manage.py dbshell

db_migrate:
    python manage.py migrate --settings=my_project.base
    python manage.py migrate --settings=my_project.test

db_reset: db_drop db_create db_migrate

.PHONY: test db_drop db_create db_migrate db_reset

Then you can do things like: $ make db_reset


use "python manage.py sqlflush" command in windows 10 for others type manage.py

참고URL : https://stackoverflow.com/questions/3414247/how-to-drop-all-tables-from-the-database-with-manage-py-cli-in-django

반응형