How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?
如何使用Django创建一个复合(复合)主键/唯一键的模型(以及表)?
3 个解决方案
#1
32
Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together
.
Django不支持复合主键。您可以使用元.unique_together创建一个唯一的复合键。
#2
5
if you want only unique mixed fields together use belowcode:
如果您想要唯一的混合字段一起使用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:
但是如果你想要唯一的一起和一个列是主列,为模型列设置主参数,类似于下面的代码:
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField(primary_key=True)
key2 = models.IntegerField()
#3
2
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. One of the entities is called tracks, which holds details of the tracks on a CD. This has a composite key of CD name, track number.
例如,您有一个保存CD集合的数据库。其中一个实体叫做磁道,它在CD上保存磁道的细节,它有一个复合键CD名称,磁道号。
#1
32
Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together
.
Django不支持复合主键。您可以使用元.unique_together创建一个唯一的复合键。
#2
5
if you want only unique mixed fields together use belowcode:
如果您想要唯一的混合字段一起使用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:
但是如果你想要唯一的一起和一个列是主列,为模型列设置主参数,类似于下面的代码:
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField(primary_key=True)
key2 = models.IntegerField()
#3
2
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. One of the entities is called tracks, which holds details of the tracks on a CD. This has a composite key of CD name, track number.
例如,您有一个保存CD集合的数据库。其中一个实体叫做磁道,它在CD上保存磁道的细节,它有一个复合键CD名称,磁道号。