What do you do when ‘makemigrations’ is telling you About your Lack of Default Value

So you added a few fields on a model. You’re happy about the new model fields and you’re excited to deploy it to your server.

You throw the following into your commandline.

$ ./manage.py makemigrations

Despite your giddiness that people will be working on your new models and you’re going to impress your boss and your friends, you receive the following message:

You are trying to add a non-nullable field 'first_name' to choice without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:

Oh, no! Now what do you do?

The reason you are getting this prompt is because, your database isn’t empty. The model that you updated with new fields, already has records saved.

Therefore, Django needs to add defaults to those records that already exist.

How do you add a default to your model? How do you add a default to your models?

Let’s say your new model looks like this:

class Subscriber(models.Model):
     first_name = models.CharField(max_length=50)
     # ... the rest of your model ...

How do you add a default to this new field? Quite simply:

class Subscriber(models.Model):
     first_name = models.CharField(max_length=50, default=None)

Then, when you call ‘makemigrations’ again:

$ ./manage.py makemigrations
Migrations for 'subscriber':
     - Add field firstname to subscriber

Simple! You now have a new field and you got rid of that annoying prompt!

Struggle with the Django Documentation?

If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!

Powered by ConvertKit