[Answered ]-Django rename model. New django_content_type is created instead of renaming the old record

1๐Ÿ‘

โœ…

I just used this on a project; the caveat being that this works without issue if you create the migration before youโ€™ve already tried to apply the automatically-created model rename migration.

Youโ€™ll want to change the app name, the model names, and the previous migration to match your setup; in this example we changed the name of a model from profile to member.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations
from django.conf import settings

sql = """UPDATE django_content_type
         SET name = 'member',
             model = 'member'
         WHERE name = 'profile' AND
               model = 'profile' AND
               app_label = 'open_humans';"""

reverse_sql = """UPDATE django_content_type
                 SET name = 'profile',
                     model = 'profile'
                 WHERE name = 'member' AND
                       model = 'member' AND
                       app_label = 'open_humans';"""


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('open_humans', '0004_auto_20150106_1828'),
    ]

    operations = [
        migrations.RunSQL(sql, reverse_sql)
    ]

1๐Ÿ‘

I can share this migration operation written for this issue:

from django.db import migrations
from django.contrib.contenttypes.models import ContentType


class UpdateContentType(migrations.RunPython):
    '''Database migration operation to update a ContentType'''

    def _update_contenttype_func(self, old_app: str, old_model: str, new_app: str, new_model: str):
        def func(apps, schema_editor):
            ContentType.objects \
                .filter(app_label=old_app, model=old_model) \
                .update(app_label=new_app, model=new_model)
            ContentType.objects.clear_cache()
        return func

    def __init__(self, app: str, model: str, new_app: str = None, new_model: str = None):
        if new_app is None:
            new_app = app
        if new_model is None:
            new_model = model
        self.app = app
        self.model = model
        self.new_app = new_app
        self.new_model = new_model
        super().__init__(
            code=self._update_contenttype_func(
                old_app=app, old_model=model, new_app=new_app, new_model=new_model
            ),
            reverse_code=self._update_contenttype_func(
                old_app=new_app, old_model=new_model, new_app=app, new_model=model
            ),
        )

    def describe(self):
        return (f"Update ContentType {self.app}.{self.model}"
                f" to {self.new_app}.{self.new_model}")

Whenever a model is renamed, I edit the migration file and add an UpdateContentType operation too:

from django.db import migrations
from apps.utils.migrations_util import UpdateContentType

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0010_previous_migration'),
        ('contenttypes', '0002_remove_content_type_name'),
    ]

    operations = [
        migrations.RenameModel(old_name='OldModel', new_name='NewModel'),
        UpdateContentType(app='myapp', model='oldmodel', new_model='newmodel'),
    ]

Leave a comment