how to add new column in django

Step 1: Open the models.py file of the app where you want to add a new column.

Step 2: Import the necessary modules. Add the following line at the top of the models.py file:

from django.db import models

Step 3: Locate the model class where you want to add a new column.

Step 4: Add a new field to the model class. Choose the appropriate field type based on your requirements. For example, to add a CharField, use the following syntax:

class YourModelName(models.Model):
    # Existing fields...
    existing_field = models.CharField(max_length=100)

    # New field
    new_field = models.CharField(max_length=50)

Step 5: Run the following commands to create and apply the migration:

python manage.py makemigrations
python manage.py migrate

Step 6: Update the database by applying the migration:

python manage.py migrate

Step 7: If you want to add a default value to the new field, you can do it in the migration file created in the "migrations" folder. Locate the migration file and find the operations list. Add a default value using the default attribute:

class MigrationName(migrations.Migration):
    # Other migration code...

    operations = [
        # Existing operations...

        migrations.AddField(
            model_name='yourmodelname',
            name='new_field',
            field=models.CharField(default='default_value', max_length=50),  # Set your default value
        ),
    ]

Step 8: Run the migration again to apply the default value:

python manage.py migrate