Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one table has more than one primary key in Django?

Tags:

django

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
like image 850
Katsuya Obara Avatar asked Sep 16 '25 17:09

Katsuya Obara


2 Answers

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'),)
like image 177
ruddra Avatar answered Sep 19 '25 06:09

ruddra


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.

like image 26
Manish Gupta Avatar answered Sep 19 '25 07:09

Manish Gupta