I have a model like this:
JavaScript
x
4
1
class Hop(models.Model):
2
migration = models.ForeignKey('Migration')
3
host = models.ForeignKey(User, related_name='host_set')
4
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.
JavaScript
1
11
11
1
class Hop(models.Model):
2
migration = models.ForeignKey('Migration')
3
host = models.ForeignKey(User, related_name='host_set')
4
5
class Meta:
6
constraints = [
7
models.UniqueConstraint(
8
fields=['migration', 'host'], name='unique_migration_host_combination'
9
)
10
]
11
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
JavaScript
1
7
1
class Hop(models.Model):
2
migration = models.ForeignKey('Migration')
3
host = models.ForeignKey(User, related_name='host_set')
4
5
class Meta:
6
unique_together = (("migration", "host"),)
7
It would act as a “surrogate” primary key column.
If you really want to create a multi-column primary key, look into this app