Django에서 manage.py CLI를 사용하여 데이터베이스에서 모든 테이블을 삭제하려면 어떻게 해야 합니까?
manage.py 및 명령줄을 사용하여 데이터베이스에서 모든 테이블을 드롭하려면 어떻게 해야 합니까?관리를 실행할 수 있는 방법이 있습니까?에서 실행할 수 있도록 적절한 파라미터를 사용하여 py를 설정합니다.NET 어플리케이션
제가 알기로는 모든 테이블을 폐기하는 관리 명령어는 없습니다.Python을 해킹하는 것을 꺼려하지 않는다면, 그것을 위해 자신만의 커스텀 명령어를 작성할 수 있습니다. 게 있을 거예요.sqlclear옵션이 흥미롭습니다.으로는 '하다'라고 되어 있습니다../manage.py sqlclear DROP TABLE SQL 입니다.
업데이트: 완전한 답변을 위해 이 답변 아래에 있는 @Mike DeSimone의 코멘트를 뻔뻔하게 인용합니다.
./manage.py sqlclear | ./manage.py dbshell
1으로 현재 1.9입니다../manage.py sqlflush
모든 테이블을 폐기할 수 있는 네이티브 장고 관리 명령어는 없습니다. 다.sqlclear ★★★★★★★★★★★★★★★★★」reset응용 프로그램 이름이 필요합니다.
그러나 Django Extensions를 설치할 수 있습니다.manage.py reset_db원하는 대로 실행할 수 있습니다(또한 보다 유용한 관리 명령어에 액세스 할 수 있습니다).
을 처리하기 South 권장), South 패키지를 할 수 ../manage.py migrate appname zero명령어를 입력합니다.
않다면, 저는 렇면면면, 면는면면 otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise otherwise?./manage.py dbshell"SQL" "SQL" "SQL" 입니다.
python manage.py migrate <app> zero
sqlclear9.1.9에서 되었습니다.
릴리스 노트에는 이행 도입이 원인이라고 기재되어 있습니다.https://docs.djangoproject.com/en/1.9/releases/1.9/
안타깝게도 모든 앱에서 동시에 작동하는 방법이나 설치된 모든 앱을 관리자로부터 나열할 수 있는 기본 제공 방법을 찾을 수 없었습니다.설치된 모든 앱을 manage와 함께 나열하는 방법.장고 파이요?
./manage.py sqlflush | ./manage.py dbshell에는 flushsqlclear 합니다.
python(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() # ...
수 cursor.execute(call_command('sqlclear', 'main'))call_command을 stdout으로 수 SQL을 사용합니다.sql_delete★★★★★★★★★★★…
psql을 사용하고 있고 django-more 2.0.0이 설치되어 있는 경우 다음 작업을 수행할 수 있습니다.
manage.py reset_schema
" " "./manage.py sqlclear ★★★★★★★★★★★★★★★★★」./manage.py sqlflush하지 않는 하려면 다음 절차를 전체를 삭제하다, 삭제하다, 삭제하다, 삭제하다, 삭제하다, 삭제해 주세요.manage.py flush.
경고: 그러면 데이터베이스가 완전히 삭제되고 모든 데이터가 손실되므로 중요하지 않은 경우 계속 시도해 보십시오.
다음은 여러 설정 파일을 사용하여 몇 가지 작업을 수행하는 Makefile 예제입니다.
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
하면 ', 하다, 하다, 하다' 할 수 요. $ make db_reset
다음 답변은 postgresql DB에 대한 것입니다.
실행: 에코 'drop owner by some_user' | ./manage.플라스틱
메모: some_user는 데이터베이스에 액세스하기 위해 사용하는 사용자의 이름입니다.settings.py 파일을 참조하십시오.
default_database = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'somedbname',
'USER': 'some_user',
'PASSWORD': 'somepass',
'HOST': 'postgresql',
'PORT': '',
}
Python을 사용하여 flush project 명령을 만듭니다.
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']])
django-extensions를 설치하여python manage.py reset_db명령어를 입력합니다.당신이 원하는 대로 할 수 있어
@peter-g으로 하다sql을 만지작거리기 apps.raw sql은 로 사용할 수.파이다은 DB를 합니다.SHOW TABLES처럼). (예: mysqlSELECT table_name FROM information_schema.tables WHERE table_schema = 'public';Postgre Postgre를 사용하는 을 합니다.,.forwards ★★★★★★★★★★★★★★★★★」backwards이행이 가능합니다.
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()))
동료/코코더는 내가 이런 짓을 한 걸 알면 날 죽일 거야
모든 표를 삭제하려면 더 간단한 답이 있습니다.데이터베이스(mydatabase.db)가 포함된 폴더로 이동하여 .db 파일을 마우스 오른쪽 버튼으로 클릭하고 "delete"를 누릅니다.구식 방식, 확실히 작동한다.
모든 테이블을 삭제하고 다시 만듭니다.
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
설명:
manage.py sqlclear " 문 " - "DROP TABLE SQL"
sed -n "2,$p"첫을 제외한 모든 . - 첫 번째 줄을 빼고요.
sed -n "$ !p" 줄을
sed "s/";/" CASCADE;/"을 (CAScade;)로.- CASCade;)는 CASCade;로 바꿉니다.
sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/"첫(BEGIN를 삽입하고 (COMMIT를 삽입합니다.- - 、 [ BEGIN; ] 、 [ COMMIT ; ]
manage.py dbshell " PASSWORD하여 ENGINE에 지정된 클라이언트를 합니다" - "ENGINE"는 USER, PASSWORD입니다.
manage.py syncdb " "INSTALLED"에 있는 앱의 되지 않은
의존관계:
- sed, Windows에서 사용하기 위해 UnxUtils: (다운로드)(설치 절차)를 설치했습니다.
크레딧:
@Manoj Govindan 및 @Mike DeSimone(sqlclear용)이 dbshell로 파이핑되었습니다.
sed "s/",/" CASCADE;/'의 @jpic
데이터베이스 및 마이그레이션을 수동으로 제거하는 솔루션.
manage.py, 작성, 작성clean.py
import os
def recursor(dirpath):
# print(dirpath)
delfiles = []
deldirs = []
with os.scandir(dirpath) as l1:
for e1 in l1:
if not e1.is_file():
with os.scandir(e1.path) as l2:
for e2 in l2:
if e2.name == 'migrations':
with os.scandir(e2.path) as l3:
for e3 in l3:
if not e3.name == '__init__.py':
print(e3.path)
if e3.is_file():
delfiles.append(e3.path)
else:
deldirs.append(e3.path)
with os.scandir(e3.path) as l4:
for e4 in l4:
delfiles.append(e4)
yn = input('are you sure to delete all the files above?(y/n)')
if yn == 'y':
for dp in delfiles:
os.remove(dp)
for dp in deldirs:
os.rmdir(dp)
recursor(os.path.dirname(os.path.realpath(__file__)))
db.sqlite3clean.py
manage 라고 하는 다른 타입의 경우는, Windows 10 에서 「manage.py sqlflush」커맨드를 사용합니다.화이
언급URL : https://stackoverflow.com/questions/3414247/how-to-drop-all-tables-from-the-database-with-manage-py-cli-in-django
'programing' 카테고리의 다른 글
| 경고: 헤더 정보를 수정할 수 없습니다. 헤더는 이미 ERROR에 의해 전송되었습니다. (0) | 2023.02.03 |
|---|---|
| 디렉토리가 비어 있는지 확인하기 위해 PHP를 사용하는 방법은 무엇입니까? (0) | 2023.02.03 |
| 여러 Vue 애플리케이션, 여러 엔트리 파일, 동일한 Vuex/Vue3 Compostition Api 스토어 [반응성 상실] (0) | 2023.02.03 |
| @SmallTest, @Medium의 목적은 무엇입니까?Android에서 테스트 및 @LargeTest 주석을 사용하시겠습니까? (0) | 2023.02.03 |
| 가비지 컬렉션이 문제가 될 경우 Spring Batch가 프로그램이 9400만 건의 트랜잭션을 중지하는 것을 막을 수 있습니까? (0) | 2023.02.03 |