[英]Compound/Composite primary/unique key with Django
如何使用Django使用复合(复合)主/唯一键创建模型(以及表格)?
Django does not support compound primary keys. Django不支持复合主键。 You can create a single compound unique key with Meta.unique_together
. 您可以使用Meta.unique_together
创建单个复合唯一键。
if you want only unique mixed fields together use belowcode: 如果您只想使用唯一的混合字段,请使用以下代码:
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField()
key2 = models.IntegerField()
But if you want unique together and one of column be primary, set primary
argument for model column, similar below code: 但是如果你想要唯一的并且其中一列是主要的,请为模型列设置primary
参数,类似下面的代码:
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField(primary_key=True)
key2 = models.IntegerField()
A composite key consists of more than one attribute to uniquely identify an entity occurrence. 复合键由多个属性组成,用于唯一标识实体事件。 This differs from a compound key in that one or more of the attributes, which make up the key, are not simple keys in their own right. 这与复合键的不同之处在于构成键的一个或多个属性本身不是简单键。
For example, you have a database holding your CD collection. 例如,您有一个包含CD集合的数据库。 One of the entities is called tracks, which holds details of the tracks on a CD. 其中一个实体称为轨道,它保存CD上轨道的细节。 This has a composite key of CD name, track number. 它有一个CD名称,轨道号的复合键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.