Home > Software design >  You are trying to add a non-nullable field 'id' to contact_info without a defaultt
You are trying to add a non-nullable field 'id' to contact_info without a defaultt

Time:09-06

I am using the command python manage.py makemigrations

However, I get this error:

You are trying to add a non-nullable field 'id' to contact_info 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

Here is models.py:

class Posts(models.Model):
    id = models.AutoField(primary_key=True)
    post_uesr = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,related_name='create_user')
    post_title = models.CharField(max_length=200)
    post_description = models.TextField(max_length=800, null=True, blank=True)
    post_likes = models.IntegerField(default=0)
    post_date = models.DateTimeField(default=datetime.now)

    def __str__(self):
        return f'{self.post_uesr}'

CodePudding user response:

it's telling you should specified a default value for your id.

ask you for adding manually or add a field with no default value.

for example for using uuid as your id:

import uuid
id = models.AutoField(default=uuid.uuid4, primary_key=True)

CodePudding user response:

It's not a bug, it's documented and logical. You add a new field, which is (by best practice, as you noticed) not NULLable so django has to put something into it for the existing records .

You can press 1 so this option applies

 1) Provide a one-off default now (will be set on all existing rows)

so just press 1, if thats your case as value. else if you want to abort this task and provide manually press 2 and this option applies.

 2) Quit, and let me add a default in models.py

BUT here in your case id is a default field already included in every table you create and that will be default to primary key.

And if you are looking to add another AutoField probably this will help

order = models.AutoField(primary_key=False)

And if you are trying to make primary key as uuid4 format

import uuid
id = models.AutoField(default=uuid.uuid4, primary_key=True)
  • Related