Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed

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.


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)