How can set two primary key fields for my models in Django


Question

I have a model like this:

class Hop(models.Model):
    migration = models.ForeignKey('Migration')
    host = models.ForeignKey(User, related_name='host_set')

I want to migration and host both together be the primary key.

1
44
4/5/2019 5:52:25 PM

Accepted Answer

I would implement this slightly differently.

I would use a default primary key (auto field), and use the meta class property, unique_together

class Hop(models.Model):
    migration = models.ForeignKey('Migration')
    host = models.ForeignKey(User, related_name='host_set')

    class Meta:
        unique_together = (("migration", "host"),)

It would act as a "surrogate" primary key column.

If you really want to create a multi-column primary key, look into this app

66
5/29/2013 3:26:28 AM

Currently, Django models only support a single column primary-key. If you don't specific primary_key = True for the field in your model, Django will automatically create a column id as a primary key.

The attribute unique_together in class Meta is only constraints for your data.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon