How to create a primary key consists of two fields

2020-06-18 02:29发布

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.

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?

2条回答
Anthone
2楼-- · 2020-06-18 03:11

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.

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.

查看更多
甜甜的少女心
3楼-- · 2020-06-18 03:23

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

unique_together = ("name", "related_name")
查看更多
登录 后发表回答