Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django migrations. How to check if table exists in migrations?

I'm currently working on app built on Django 1.8 and Postgres. This app is installed in several environments, in some of them there old tables in DB from which i need to delete records.

I wrote migration with following SQL query:

IF EXISTS (
    SELECT relname FROM pg_class WHERE relname=tablename
) THEN 
    DELETE FROM tablename END IF;

But Django throws error at this query:

django.db.utils.ProgrammingError: syntax error at or near "IF" 

Can i somehow check, in migration, that table exists, and only then execute query, like DROP FROM tablename ?

like image 211
Grigoriy Mikhalkin Avatar asked Nov 11 '16 11:11

Grigoriy Mikhalkin


Video Answer


1 Answers

The easiest way to check if a table exists is to use django.db.connection.introspection.table_names():

from django.db import connection

...

all_tables = connection.introspection.table_names()
old_tables = set('old_table_1', 'old_table_2')
existing_old_tables = old_tables.union(all_tables)
# clean tables in existing_old_tables with migrations.RunSQL() as suggested above
like image 98
mrts Avatar answered Oct 27 '22 13:10

mrts