如何创建主键包含Django中的两个字段?

时间:2022-05-08 21:04:51

I develop a certain application, which I found with the specified database and model schema. I am using Django version 1.8.2. Below is presented a problem. Unnecessary fields have been omitted, model names are invented for the purposes of an example, because I can not disclose. Consider the following models A and B.

我开发了一个特定的应用程序,我发现它与指定的数据库和模型架构。我正在使用Django版本1.8.2。下面是一个问题。不必要的字段已被省略,模型名称是出于示例目的而发明的,因为我无法透露。考虑以下模型A和B.

class B (models.Model):

      name = models.CharField(max_length=100)

class A (models.Model):

      name = models.CharField(max_length=100, primary_key=True)
      related_name = models.ForeignKey(B, null=True, blank=True)

After a long time a project the possibility that there may be several of the same name A, but with different foreign key B. In this particular case, I would like to model the primary key "A" consisted of two fields: name and related name. How to create such a key consists of two fields in django?

经过很长一段时间的项目可能有几个相同的名字A,但有不同的外键B.在这个特殊的情况下,我想建模主键“A”由两个字段组成:名称和相关名称。如何创建这样一个键由django中的两个字段组成?

2 个解决方案

#1


3  

You want to use a composite key. Django does not support this See here. There is some support but you can't have relationships so it's pretty limited as far as practical usage.

您想使用复合键。 Django不支持这一点。有一些支持,但你不能有关系,所以它的实际用途非常有限。

Currently Django models only support a single column in this set, denying many designs where the natural primary key of a table is multiple columns. Django currently can't work with these schemas; they must instead introduce a redundant single-column key (a “surrogate” key), forcing applications to make arbitrary and otherwise-unnecessary choices about which key to use for the table in any given instance.

目前,Django模型仅支持此集合中的单个列,拒绝许多设计,其中表的自然主键是多列。 Django目前无法使用这些模式;它们必须引入冗余的单列密钥(“代理”密钥),迫使应用程序在任何给定实例中对表使用哪个密钥进行任意和其他不必要的选择。

#2


2  

Django does not support composite keys. But you could use unique-together

Django不支持复合键。但你可以一起使用独特的

unique_together = ("name", "related_name")

#1


3  

You want to use a composite key. Django does not support this See here. There is some support but you can't have relationships so it's pretty limited as far as practical usage.

您想使用复合键。 Django不支持这一点。有一些支持,但你不能有关系,所以它的实际用途非常有限。

Currently Django models only support a single column in this set, denying many designs where the natural primary key of a table is multiple columns. Django currently can't work with these schemas; they must instead introduce a redundant single-column key (a “surrogate” key), forcing applications to make arbitrary and otherwise-unnecessary choices about which key to use for the table in any given instance.

目前,Django模型仅支持此集合中的单个列,拒绝许多设计,其中表的自然主键是多列。 Django目前无法使用这些模式;它们必须引入冗余的单列密钥(“代理”密钥),迫使应用程序在任何给定实例中对表使用哪个密钥进行任意和其他不必要的选择。

#2


2  

Django does not support composite keys. But you could use unique-together

Django不支持复合键。但你可以一起使用独特的

unique_together = ("name", "related_name")