Django PostgreSQL - delete all tables?

Here is how I can do this when MySQL is the backend,

    cursor.execute('show tables')
    rows = cursor.fetchall()
    for row in rows:
        cursor.execute('drop table %s; ' % row[0]) 

But how can I do this when postgresql is the backend?

+3
source share
5 answers

You can use select * from pg_tables;get a list of tables, although you probably want to exclude where schemaname <> 'pg_catalog'...

Based on another one of your last questions, if you are trying to just drop all your django stuff, but don’t have permission to delete the database, you can just MAKE SURE the Django has it all?

Also use CASCADE on your frame .

EDIT: can you select * from information_schema.tables;?

EDIT: row[2] row[0], , WHERE schemaname = 'my_django_schema_here'.

EDIT: SELECT table_name from pg_tables where schemaname = 'my_django_schema_here'; row[0]

+3
    cursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type != 'VIEW' AND table_name NOT LIKE 'pg_ts_%%'""")
    rows = cursor.fetchall()
    for row in rows:
        try:
            cursor.execute('drop table %s cascade ' % row[0])
            print "dropping %s" % row[0]
        except:
            print "couldn't drop %s" % row[0]

http://www.siafoo.net/snippet/85

+3

, ./manage.py sqlclear SQL- DROP TABLE (-) .

+3

script , script, phoenixdb.sh, DB , - . , Dev .

set -e
python manage.py dbshell <<EOF
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
EOF

python manage.py migrate

db db. Django , :

alter schema public owner to django-db-user-name; 

db

alter database django-db-name owner to django-db-user-name;
+1

\dtis the equivalent command in postgres to display tables. Each row will contain values ​​for (schema, Name, Type, Owner), so you should use a second ( row[1]) value.

In any case, the solution will break (in MySQL and PostgreSQL) when foreign key constraints are involved, and if they are not, you may encounter sequences. Thus, the best way, in my opinion, is to simply delete the entire database and call initdb again (which is also a more efficient solution).

0
source

Source: https://habr.com/ru/post/1756254/


All Articles