ADD Column - Django

0

How can I add a column to a table in the database using django? I tried the following migration and did not update my table:

from django.db import models, migrations

class Migration(migrations.Migration):
    dependencies = [
        ('api', '0001_initial')
    ]
operations = [
    migrations.AddField(
        model_name='item',
        name='name',
        field=models.CharField(max_length=45)
    )
]
    
asked by anonymous 18.10.2018 / 15:29

1 answer

1

Unless you are not using the django ORM, this operation is done automatically by the framework. Follow the steps below:

Go to the models.py file of your app, in the definition of the model and simply add the column, for example let's say the original definition is:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

And you want to add the column age , change the Person class to:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    age = models.IntegerField()

Then at the root of your project, using the manage.py script, create the migration with the command:

$ python manage.py makemigrations

Finally update the database with the command:

$ python manage.py migrate 
    
18.10.2018 / 21:55