Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new field to a model with new Django migrations?

I'm using the contribute_to_class method but I don't know how to create the field in the database with new migrations.

like image 472
pedro_witoi Avatar asked Jun 19 '14 16:06

pedro_witoi


People also ask

How do I update model fields in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

What is the difference between Makemigrations and migrate in Django?

makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.


1 Answers

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

To avoid dealing with errors for your existing models however, you can use the --fake:

  1. Initialize migrations for your existing models:

    ./manage.py makemigrations myapp 
  2. Fake migrations for existing models:

    ./manage.py migrate --fake myapp 
  3. Add the new field to myapp.models:

    from django.db import models  class MyModel(models.Model):     ... #existing fields     newfield = models.CharField(max_length=100) #new field 
  4. Run makemigrations again (this will add a new migration file in migrations folder that add the newfield to db):

    ./manage.py makemigrations myapp 
  5. Run migrate again:

    ./manage.py migrate myapp 
like image 153
Nima Avatar answered Sep 28 '22 11:09

Nima