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':
  0002_subscriber_first_name.py:
     - Add field firstname to subscriber

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




Need help with Django REST Framework? Django REST Framework documentation a little confusing?

Join me for my FREE Django REST Framework email course:

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • JQuery Integration
  • AngularJS Integration
Powered by ConvertKit


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