Django 多对一 IntegrityError

Django Many-To-One IntegrityError

我是 Python 和 Django 的新手。由于文档,我创建了数据库。我测试了它,两个模型之间的多对一关系有错误。

我觉得这很奇怪,因为它们之间的关系就像一对一的关系 类 但是如果我尝试添加很多,它会出错。还有其他 类 与多对一关系相同。我以相同的方式创建,它们工作得很好。顺便说一句,我正在使用sqlite。

class unites (models.Model):
    id = models.IntegerField(primary_key=True)
    unitename = models.CharField(max_length=128)


class intensivecare_forms (models.Model):
    id = models.IntegerField(primary_key=True)
    hospitals_id = models.ForeignKey(hospitals, on_delete=models.CASCADE)
    formname = models.CharField(max_length=128)
    data = models.JSONField()
    unites_id = models.ForeignKey(unites, on_delete=models.CASCADE)

如果我尝试将第二种形式添加到 unites 中,它会出现此错误。

IntegrityError at /admin/LocalManager/intensivecare_forms/add/

UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id

Request Method:     POST
Request URL:    http://localhost:8000/admin/LocalManager/intensivecare_forms/add/
Django Version:     3.2.4
Exception Type:     IntegrityError
Exception Value:    

UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id

Exception Location:     /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python Version:     3.9.6

unites_id 最初是 OneToOneFieldOneToOneField 基本上是 ForeignKeyunique=True,因此两个 intensivecare_forms 不能指向同一个 unites.

后来你把它变成了ForeignKey,但是忘记迁移数据库了,所以UNIQUE约束还是由数据库强制执行的。

通过makemigrationsmigrate,通常可以去掉UNIQUE约束,从而让两个intensivecare_forms指向相同的 unites.