Skip to content

Instantly share code, notes, and snippets.

@benzkji
Last active December 6, 2017 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benzkji/e3159967069a2d1676ba65458beb2592 to your computer and use it in GitHub Desktop.
Save benzkji/e3159967069a2d1676ba65458beb2592 to your computer and use it in GitHub Desktop.
rename-tables-for-django.py (needed for updates to django-cms 3.0)
=> ./manage.py datamigration your_app rename_plugin_tables
def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_names = connection.introspection.table_names()
for source, destination in table_mapping:
if source in table_names and destination in table_names:
print u" WARNING: not renaming {0} to {1}, because both tables already exist.".format(source, destination)
elif source in table_names and destination not in table_names:
print u" - renaming {0} to {1}".format(source, destination)
db.rename_table(source, destination)
def rename_tables_old_to_new(db, table_mapping):
return rename_tables(db, table_mapping, reverse=False)
def rename_tables_new_to_old(db, table_mapping):
return rename_tables(db, table_mapping, reverse=True)
class Migration(DataMigration):
cms_plugin_table_mapping = (
# (old_name, new_name),
('cmsplugin_whateverplugin', 'my_app_whateverplugin'),
)
def forwards(self, orm):
rename_tables_old_to_new(db, self.cms_plugin_table_mapping)
# ...
def forwards_cmsplugins_automagically(self, orm):
"""
does it all automagically. take care!
"""
from cms.plugin_pool import plugin_pool
mapping = []
for plugin in plugin_pool.get_all_plugins():
if plugin.model._meta.db_table.startswith('cmsplugin_'):
old = plugin.model._meta.db_table
# warning, no good if your plugin has "cmsplugin" in its tablename on itself...
new = plugin.model._meta.db_table.replace(
'cmsplugin',
plugin.model._meta.app_label,
)
mapping.append((old, new))
print mapping
print "paste this mapping above in the code, to go back again!"
rename_tables_old_to_new(db, mapping)
def backwards(self, orm):
rename_tables_new_to_old(db, self.cms_plugin_table_mapping)
def backwards_automagic_to_be_done(self, orm):
rename_tables_new_to_old(db, self.cms_plugin_table_mapping)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment