Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed

断了今生、忘了曾经 提交于 2019-12-03 15:51:04

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.

A met a bit different situation with the same error. The problem was that I use 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)

SULUTION

class Column(models.Model):
    ...

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!