[Fixed]-Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed

9๐Ÿ‘

โœ…

The documentation says two things:

  1. If you have ForeignKey constraints they are now enforced at the database level. So make sure youโ€™re not violating a foreign key constraint. Thatโ€™s the most likely cause for your issue, although that would mean youโ€™d have seen these issues with other databases. Look for patterns like this in your code:

    # in pagetree/models.py, line 810
    @classmethod
    def create_from_dict(cls, d):
        return cls.objects.create()  # what happens to d by the way?
    

    This will definitely fail with a ForeignKey constraint error since a PageBlock must have section, so you canโ€™t call create without first assigning it.

  2. If you circumvent the foreign key constraint by performing an atomic transaction (for example) to defer committing the foreign key, your Foreign Key needs to be INITIALLY DEFERRED. Indeed, your test db should already have that since itโ€™s rebuilt every time.

๐Ÿ‘คdirkgroten

9๐Ÿ‘

I met a different situation with the same error. The problem was that I used the same Model name and field name

Incorrect code:

class Column(models.Model):
    ...

class ColumnToDepartment(models.Model):
    column = models.ForeignKey(Column, on_delete=models.CASCADE)

Solution:

class Column(models.Model):
    ...

class ColumnToDepartment(models.Model):
    referring_column = models.ForeignKey(Column, on_delete=models.CASCADE)
๐Ÿ‘คYuriy Gyerts

2๐Ÿ‘

๐Ÿ‘คKrzysieqq

2๐Ÿ‘

In my case, I found that the ForeignKey object that my model refers to does not exist.
Therefore, I change the referenced FK object to the existing object.

1๐Ÿ‘

A reason could be you miscalculated what happens when you delete an item from the db that is linked with a foreign key to something else, elsewhere.

p.e. what happens when you delete an author that has active books?

I donโ€™t meant to enter into the logic of the application, but consider for example to cascade the deletion of the elements linked to that key.

Here is an example, in this case we are dealing with "post" attribute for each "user"

user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)

Hereโ€™s a careful explanation, Django 4.0:
https://docs.djangoproject.com/en/4.0/ref/models/fields/

๐Ÿ‘คCarlo

0๐Ÿ‘

I just had this error: sqlite3.IntegrityError: FOREIGN KEY constraint failed on my Django project. Turns out I deleted the migrations folder somewhere along the line so it didnโ€™t pick up my model changes when I ran python manage.py makemigrations. Just make sure you still have a migrations folder with migrations in.

0๐Ÿ‘

One more thing to check, in my case it was related to my fixtures files.
Regenerating them after migration to Django3 solved the issue I had while testing my app.

./manage.py dumpdata app.Model1 app.Model2 --indent=4 > ./app/fixtures/file.json
๐Ÿ‘คTheo Godard

0๐Ÿ‘

When I have trouble with migrations or tables, I do it and it very often helps:

  1. Comment your trouble strings;
  2. Do python3 manage.py makemigrations and python3 manage.py migrate;
  3. Then u must do python3 manage.py migrate --fake;
  4. Uncomment your strings and do it again python3 manage.py makemigrations and python3 manage.py migrate.

I hope it is useful for u

๐Ÿ‘คBlock2busted

0๐Ÿ‘

My problem was solved after doing the migration, because I have altered the foreign key and then didnโ€™t apply the migrations.

Specifically, at first I have the following piece of code in models:

class TeacherRequest(models.Model):
    requester = models.ForeignKey(
        Profile,
        on_delete=models.CASCADE,
        related_name="teacher_request",
    )

    class RequestStatus(models.TextChoices):
        PENDING = '1', _('pending')
        APPROVED = '2', _('approved')
        REJECTED = '3', _('rejected')

    status = models.CharField(
        choices=RequestStatus.choices,
        max_length=1,
        default=RequestStatus.PENDING,
    )

Then I have changed the foreign key from Profile to User:


class TeacherRequest(models.Model):
    requester = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="teacher_request",
    )

    class RequestStatus(models.TextChoices):
        PENDING = '1', _('pending')
        APPROVED = '2', _('approved')
        REJECTED = '3', _('rejected')

    status = models.CharField(
        choices=RequestStatus.choices,
        max_length=1,
        default=RequestStatus.PENDING,
    )

Solution

python manage.py makemigrations
python manage.py migrate
๐Ÿ‘คMostafa Ghadimi

0๐Ÿ‘

Most probably the cause of the error is the lacking of matching Foreignkey elements in your model and the one your trying to save(update using that foreignkey).
Make sure that the foreignkey constraints(value) are present in both your and the new data

๐Ÿ‘คabhishek khot

0๐Ÿ‘

I met a different situation with the same error.

The problem was that i had my on_delete attributes set to DO_NOTHING, which ended up violating foreign key constraints.

Setting it to SET_NULL fixed it for me.

๐Ÿ‘คoruchkin

Leave a comment