如何在 Django 中为我的模型设置两个主键字段 [英] How can I set two primary key fields for my models in Django
本文介绍了如何在 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
这篇关于如何在 Django 中为我的模型设置两个主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文