How to set the default value of a column to NULL in Django

To set the default value of a column to NULL in Django, you can use the null=True parameter when defining the field in your model. Here's an example:


from django.db import models

class YourModel(models.Model):
    your_field_name = models.CharField(max_length=100, null=True)

In the above code, the your_field_name field is defined with null=True. This allows the field to have a NULL value, meaning it can be empty or not set for a particular record.

After making changes to your model, you need to create and apply a database migration to update the corresponding database table. You can generate the migration files using the following commands:


python manage.py makemigrations
python manage.py migrate

These commands will create the necessary migration files and apply the changes to the database.

By setting null=True, the default value for the column will be NULL, unless you explicitly set a different value for the field when creating or updating a record.

Comments

Leave a Reply