Home > other >  Its impossible to add a non-nullable field 'profile' to post without specifying a default.
Its impossible to add a non-nullable field 'profile' to post without specifying a default.

Time:06-09

i created a model named post where i didn't add a 'PROFILE' foreign key before.

class Post(models.Model):
    profile = models.ForeignKey(profile, on_delete=models.CASCADE)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    caption = models.CharField(max_length=250, blank=True, null=True)
    image = models.ImageField(upload_to="post_images", blank=True, null=True)
    created = models.DateTimeField(default=datetime.now())
    no_of_likes = models.IntegerField(default=0)

later i added it & ran makemigrations, it returned me saying i need to provide a default. by mistake i added the id number of that profile model as default. then everytime i do migrate, it returns IntegrityError: The row in table 'App_post' with primary key '6b6b280dbce848acb9fbbbec677d01b1' has an invalid foreign key: App_post.profile_id contains a value '1' that does not have a corresponding value in App_profile.id.

now even after i completely removed the profile row from the post model, it still returns me saying this when i migrate. how do i fix this?? i want to change the default yet it returns saying App_post.profile_id contains a value '1' that does not have a corresponding value in App_profile.id i removed 1 from defult, i removed the whole row yet it doesn't change. i had to startover a whole project for this reason once, please help!!

CodePudding user response:

Go to migrations, edit the migration file where you had made that profile migration and you'll see

operations = [
        migrations.AddField(
            model_name='post',
            name='profile ',
            field=models.ForeignKey(default=1), #your field
            preserve_default=False, 
        ),
    ]

just comment that full and then run migrate. after commenting it should look something like below:

operations = [
        # migrations.AddField(
        #     model_name='post',
        #     name='profile ',
        #     field=models.ForeignKey(default=1),
        #     preserve_default=False,
        # ),
    ]
  • Related