Renaming models(tables) in Django
Asked Answered
E

1

11

so I've already created models in Django for my db, but now want to rename the model. I've change the names in the Meta class and then make migrations/migrate but that just creates brand new tables.

I've also tried schemamigration but also not working, I'm using Django 1.7

Here's my model

class ResultType(models.Model):
    name = models.CharField(max_length=150)
    ut = models.DateTimeField(default=datetime.now)
    class Meta:
       db_table = u'result_type'

    def __unicode__(self):
        return self.name

Cheers

Emmeram answered 27/11, 2014 at 16:26 Comment(0)
A
26

Django does not know, what you are trying to do. By default it will delete old table and create new. You need to create an empty migration, then use this operation (you need to write it by yourself):

https://docs.djangoproject.com/en/stable/ref/migration-operations/#renamemodel

Something like this:

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel("OldName", "NewName")
    ]
Ambry answered 27/11, 2014 at 16:28 Comment(8)
I think my django is out of sync, error "Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them" I've deleted all the 0001_initial.py and then created an migration with my new class..Emmeram
I want to rename a table because I'm renaming the app. How can I achieve that?Redraft
So to create an empty migration: ./manage.py makemigrations --empty myapp.Doldrums
NameError: name 'operations' is not defined. The docs don't have any examples, so not very useful.Evelinaeveline
Following this question, it seems that operations (inside the list) above should be migrations. I changed that word and my code worked.Evelinaeveline
@Deleet obviously, for the my example you should import from django.db.migrations import operationsAmbry
Tried that. Did not work. Substituting the word as described above worked.Evelinaeveline
The docs says: This will look like you deleted a model with the old name and added a new one with a different name, and the migration it creates will lose any data in the old table.Curdle

© 2022 - 2024 — McMap. All rights reserved.