Florent
Florent

Reputation: 1928

What is the rule for default value in Django fields?

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

Upvotes: 2

Views: 1796

Answers (1)

saharbit
saharbit

Reputation: 66

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

Upvotes: 1

Related Questions