I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error while using
python manage.py migrate
. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key.
here's the code :
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
here's the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
CodePudding user response:
Your issue is that that there are existing notes in the database that do not have a author_id
field, but you have not set a default value and neither allowed to to be kept blank. Thus it's a IntegrityError
to add the field.
You can solve this in 2 ways:
Allow the field to be blank
- Delete the last migration in your migrations folder
- Edit the author field like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
- Run makemigrations and migrate
Set a default value for the field
- Delete the last migration from the migrations folder. You can also edit it but simply deleting it is easiest
- Run makemigrations again
- During make migration, it will prompt you if you want to provide a default value for the field. Select "Provie a one of value for now"
- Type
models.User.objects.all().first()
or alternatively some other "defalt" author for existing notes - Run
migrate
You can also solve the problem by removing all existing notes from the database