10

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

Toby Green
  • 101
  • 1
  • 1
  • 3

1 Answers1

25

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")
    ]
Matt Sanders
  • 8,023
  • 3
  • 37
  • 49
coldmind
  • 5,167
  • 2
  • 22
  • 22
  • 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.. – Toby Green Nov 28 '14 at 11:20
  • I want to rename a table because I'm renaming the app. How can I achieve that? – Csaba Toth Jun 09 '16 at 22:24
  • 3
    So to create an empty migration: `./manage.py makemigrations --empty myapp`. – Ehvince Jul 12 '16 at 19:37
  • 2
    `NameError: name 'operations' is not defined`. The docs don't have any examples, so not very useful. – CoderGuy123 Oct 24 '16 at 12:21
  • 2
    Following [this question](http://stackoverflow.com/questions/25091130/django-migration-strategy-for-renaming-a-model-and-relationship-fields), it seems that `operations` (inside the list) above should be `migrations`. I changed that word and my code worked. – CoderGuy123 Oct 24 '16 at 12:29
  • @Deleet obviously, for the my example you should import `from django.db.migrations import operations` – coldmind Oct 24 '16 at 13:15
  • Tried that. Did not work. Substituting the word as described above worked. – CoderGuy123 Oct 24 '16 at 13:20
  • of course you're allowed to skip stuff in your example and tell those who point out the mistake "obviously you forgot that". of course, of course... – igorsantos07 Nov 28 '17 at 06:40
  • 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.`** – AlirezaAsadi Oct 19 '22 at 10:45