Compound/Composite primary/unique key with Django
Asked Answered
C

2

33

How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?

Closefisted answered 16/2, 2010 at 5:11 Comment(1)
I've implemented basic support for virtual Composite Keys. Suitable for getting access to an existing db, but probably, for the development it's better to keep using standard django id column. Check my answer here - https://mcmap.net/q/241257/-composite-primary-key-in-djangoControl
B
39

Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together.

Balas answered 16/2, 2010 at 5:22 Comment(5)
Thanks Ignacio! How to make this work with Many-to-Many relationship? Will it work?Closefisted
I'm really curious as to what you believe the connection between a compound unique key and a many-to-many relationship is...Balas
Say we have 2 entities: Students & Subjects. Students can take many subjects. A join table with compound primary key: Table student_subjects: -------------------------------- student_id subject_id It's a basic technique to create n-to-n relationships.Closefisted
So then just put it in the through table.Balas
Regarding many-to-many, the link referenced says: A ManyToManyField cannot be included in unique_together. (It’s not clear what that would even mean!) If you need to validate uniqueness related to a ManyToManyField, try using a signal or an explicit through model.Bulley
E
18

if you want only unique mixed fields together use belowcode:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField()
    key2 = models.IntegerField()

But if you want unique together and one of column be primary, set primary argument for model column, similar below code:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField(primary_key=True)
    key2 = models.IntegerField()
Eskew answered 25/11, 2016 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.