Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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') 

I want the primary key to be the combination of migration and host.

like image 395
Vahid Kharazi Avatar asked May 28 '13 19:05

Vahid Kharazi


People also ask

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

How do you make two fields unique in Django?

Using the constraints features UniqueConstraint is preferred over unique_together. From the Django documentation for unique_together : Use UniqueConstraint with the constraints option instead. UniqueConstraint provides more functionality than unique_together.

Does Django support composite primary key?

Django does not support composite primary keys.


2 Answers

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

like image 171
karthikr Avatar answered Oct 03 '22 00:10

karthikr


Currently, Django models only support a single-column primary key. If you don't specify 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 a constraint for your data.

like image 26
Hùng Ng Vi Avatar answered Oct 03 '22 02:10

Hùng Ng Vi