Reputation: 487
I am new to Python and Django. I created database due to documents. I tested it and there has been error to many-to-one relationship between two models.
It looks weird to me because It works like one to one relationship between those classes but it gives error if I try to add many. There are other classes with same relationship as many-to-one. I created same way and they work just fine. I am using sqlite by the way.
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)
It gives this error if I try to add second form into 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
Upvotes: 2
Views: 199
Reputation: 476659
The unites_id
was a OneToOneField
initially. A OneToOneField
is basically a ForeignKey
with unique=True
, such that two intensivecare_forms
can not point to the same unites
.
Later you turned it into a ForeignKey
, but forgot to migrate the database, so the UNIQUE
constraint was still enforced by the database.
By makemigrations
and migrate
, normally you can drop the UNIQUE
constraint, and thus let two intensivecare_forms
point to the same unites
.
Upvotes: 2