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

Posted by Chris Bartos on March 8, 2016

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!

Similar Posts

How to Implement Many-To-Many Relationship in Django
Test your Queries before they make it into Production using the Django Shell
I have a ChoiceField Callable that Includes a Queryset but it Breaks my Django app
How to filter a DateTimeField by today's date in Django
Help! My Models feel Bloated! Why you should write a custom Manager

What do you do after the Official Django Tutorial?

Here's what you'll learn:

  1. Start writing tests
  2. Increase the size / complexity of the Polls application.
  3. Learn how to code in Django by reading the Django source code.
  4. Finding code snippets to use in your website by reading the code of other websites.
  5. Using Javascript in a web app.
  6. Deploying on Heroku and AWS.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKit

Get some value from this post? Please like and share this post because more people also deserve some value. :-)