Skip to content

Instantly share code, notes, and snippets.

@sjkingo
Last active October 5, 2019 02:53
Show Gist options
  • Save sjkingo/d4815302eb4e32b0f120 to your computer and use it in GitHub Desktop.
Save sjkingo/d4815302eb4e32b0f120 to your computer and use it in GitHub Desktop.
Fix for re-adding the django_content_type.name column in Django 1.7

Django 1.8 drops the name field from ContentType in favour of a property on the model itself (see https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#the-contenttype-model).

If you update to 1.8 and then back to 1.7 (for whatever crazy reason..) you will come across exceptions as the name property doesn't exist (and neither does the database field).

These scripts restore that functionality to Django 1.7 (by recreating the field and populating it correctly).

It does not cause any data loss, but as always: Use at your own risk.

ALTER TABLE django_content_type ADD COLUMN name character varying(50) NOT NULL DEFAULT 'run migrate.py';
from django.contrib.contenttypes.models import ContentType
from django.db.models.loading import get_model
def fix_name_column():
"""
Updates the name column of ContentType to match the model's verbose_name.
"""
for t in ContentType.objects.all():
model = get_model(t.app_label, t.model)
if model is None:
name = t.model
else:
name = unicode(model._meta.verbose_name)
t.name = name
t.save()
if __name__ == '__main__':
fix_name_column()
@komuw
Copy link

komuw commented Sep 28, 2015

Thanks, God sent.

@mjpvz
Copy link

mjpvz commented Feb 22, 2018

How/where do I run that SQL statement?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment