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
.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
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.
Django does not support composite primary keys.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With