I have following table structure.
When I try to migrate, I got following error.
django.db.utils.OperationalError: table "certificate_light" has more than one primary key
However, I found other stack overflow page saying that one table can have more than one primary key in RDBMS.
Can anyone know how I can implement table having more than one primary key in Django?
models.py
class Certificate(models.Model):
name=models.CharField(max_length=20)
class Zone(models.Model):
zone=models.CharField(max_length=20)
conditioned=models.BooleanField(default=True)
class Light(models.Model):
certificate=models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate')
zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone')
lpd=models.IntegerField()
sensor=models.BooleanField(default=True)
Update
I added detail error message as below.
Applying certificate.0007_auto_20181126_1155...Traceback (most recent call last):
File "C:\Users\obakatsu\Anaconda3\envs\webEP\lib\site-packages\django\db\backends\utils.py", line 63, in execute
return self.cursor.execute(sql)
File "C:\Users\obakatsu\Anaconda3\envs\webEP\lib\site-packages\django\db\backends\sqlite3\base.py", line 326, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "certificate_light" has more than one primary key
Django does not support multiple primary key exactly. Instead you can use unique_togather. For example:
class Light(models.Model):
certificate = models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate')
zone = models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone')
lpd = models.IntegerField()
sensor = models.BooleanField(default=True)
class Meta:
unique_together = (('certificate', 'zone'),)
You can use multiple OneToOne Fields in a model along with default primary key id
. The OneToOne field also "behaves" like a primary key i.e. Cannot be same for multiple rows. On top of that, you can use unique_together
to combine the 2 unique fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With