Skip to content

Instantly share code, notes, and snippets.

@dhbradshaw
Last active August 16, 2023 17:50
Show Gist options
  • Select an option

  • Save dhbradshaw/e2bdeb502b0d0d2acced to your computer and use it in GitHub Desktop.

Select an option

Save dhbradshaw/e2bdeb502b0d0d2acced to your computer and use it in GitHub Desktop.
Rename field using migrations in django 1.7
To change a field name in django 1.7+
1. Edit the field name in the model (but remember the old field name: you need it for step 3!)
2. Create an empty migration
$ python manage.py makemigrations --empty myApp
3. Edit the empty migration (it's in the migrations folder in your app folder, and will be the most recent migration) by adding
migrations.RenameField('MyModel', 'old_field_name', 'new_field_name'),
to the operations list.
4. Apply the migration
$ python manage.py migrate myApp
@HoverHell

Copy link
Copy Markdown
  1. Create an empty migration

It is a bit easier to create an automatic migration, and replace the RemoveField + AddField pair with one RenameField (or with RenameField + AlterField if needed).

@ivancarrancho

Copy link
Copy Markdown

operations = [ migrations.RenameField('MyModel', 'old_field_name', 'new_field_name'), ]
perfect!

@amirkarimi

Copy link
Copy Markdown

I'm not sure when this feature is added to Django but just accidentally found Django 2.1.4 asks for renames when running makemigrations. At least in my case, which was location_state -> location_city.

@ocomsoft

Copy link
Copy Markdown

@amirkarimi I found this doesn't always happen - I came here from a google search because I needed to change a migration that dropped the field and added the new one instead of renaming it.

@vanessaLatefa

Copy link
Copy Markdown

HERO!!!

@MichelML

Copy link
Copy Markdown

thanks!

@SoniaStalance

Copy link
Copy Markdown

Thankyou so much!

@klchanhenry

Copy link
Copy Markdown

Great! Working !

@bradicalone

Copy link
Copy Markdown

Easier way I found:
1st: Is changing the model to the correct name you want.
2nd: Changing the file in migrations folder which usually looks like 0001_initial.py and changing the field name in the list to the correct field name you want also.
3rd: change the column name in the Database.

@srini-pen

Copy link
Copy Markdown

It's working to me. Thanks!!

@carldevzw

Copy link
Copy Markdown

💯. Thanks

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