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

2 8 picture 2 8 · May 28, 2013 · Viewed 51.5k times · Source

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.

Answer

karthikr picture karthikr · May 28, 2013

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