Skip to content
Advertisement

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

I have a model like this:

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

How can I have the primary key be the combination of migration and host?

Advertisement

Answer

Update Django 4.0

Django 4.0 documentation recommends using UniqueConstraint with the constraints option instead of unique_together.

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

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

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['migration', 'host'], name='unique_migration_host_combination'
            )
        ]

Original 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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement