CoreyMSchafer/code_snippets

Integrity Error

suravijayjilla opened this issue · 2 comments

Hi,

In the pagination video, I am tried to load the posts.json file using python shell, in post.save(),

it throws,
IntegrityError: FOREIGN KEY constraint failed

Please help me on this...

Hi,

In the pagination video, I am tried to load the posts.json file using python shell, in post.save(),

it throws,
IntegrityError: FOREIGN KEY constraint failed

Please help me on this...

To solve this I just added db_constraint=False:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False) # NEW
    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

Hi, I solve this problem by doing the following steps:

First, I tried to solve with adding db_constraint=False, but there comes posts with no user displayed on my home list. All of those posts are with user_id=2.
So, I go to python manage.py shell to check if there is some user with id 2. and I found that I only have 1, 5, 6 because I have created, deleted some users in my /admin before.

And the final solution for me is

  1. deleting all the posts in my /admin Posts, no more adding db_constraint=False, run command makemigrations and migrate for db.
  2. Change the posts.json file objects with user_id=2 to user_id=whatever your shell tells you.
  3. again open python manage.py shell and type commands in the video, and it should work.