如何在 Django 中为我的模型设置两个主键字段
问题描述:
我有一个这样的模型:
class Hop(models.Model):
migration = models.ForeignKey('Migration')
host = models.ForeignKey(User, related_name='host_set')
我希望主键是 migration
和 host
的组合.
I want the primary key to be the combination of migration
and host
.
答
我的实现方式略有不同.
I would implement this slightly differently.
我会使用默认主键(自动字段),并使用元类属性,unique_together
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