ADD Column - Django

Asked

Viewed 422 times

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)
    )
]

1 answer

2


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

Go to your app’s models.py file, model definition (class) 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 Migration with the command:

$ python manage.py makemigrations

Finally update the database with the command:

$ python manage.py migrate 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.