如何在Django中为我的模型设置两个主键字段

问题描述:

我有一个这样的模型:

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.

我会稍微不同地实现这一点.

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