1

I scratch my head trying to figure out why a default value is required on some but not all fields. For example the documentation says models.CharField() has only one mandatory option which is max_length but python manage.py makemigration return an error when a default value isn't provided. And I have the same error for some of my models.ForeignKey() fields. Could you explain why and when a default value should be provided?

models.py

class Algo(models.Model):
    strategy = models.ManyToManyField(Strategy, related_name='strategy')
    name = models.CharField(max_length=12) # <-- Return an error !?

    class Meta:
        verbose_name_plural = "algos"

    def __str__(self):
        return self.name
Florent
  • 1,791
  • 22
  • 40
  • 3
    You need to provide a `default` if you *add* or *modify* a field for a model that *already* exists, since there can be records in the database, and you need to specify what to fill in for these existing records. – Willem Van Onsem Jan 21 '20 at 16:02

1 Answers1

1

First, read about blank and null:

https://stackoverflow.com/a/8609425/9579839

Then you can better understand the default value. When you don't set blank and null to True, and you try to migrate an existing table, you need to provide the field with a one time default that will populate the now non-nullable column

Sahar
  • 66
  • 4