How to create a primary key consists of two fields in Django?

I am developing a specific application that I found with the specified database and model schema. I am using Django version 1.8.2. Below is the problem. Unnecessary fields are omitted, model names are invented as an example, because I canโ€™t open. 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 project time, it is possible that there may be several names of the same name A, but with a different foreign key B. In this particular case, I would like to model the primary key "A", consisting of two fields: name and surname. How to create such a key consists of two fields in django?

+6
source share
2 answers

You want to use a composite key. Django does not support this . See here . There is some support, but you have no relationship, so it is quite limited in practical use.

Currently, Django models support only one column in this set, denying many projects in which the table's natural primary key is multiple columns. Django is currently unable to work with these schemes; Instead, they should enter a redundant single-column key ("surrogate" key), forcing applications to make arbitrary and otherwise unnecessary choices about which key to use for the table in any given instance.

+3
source

Django does not support compound keys. But you can use unique-together

 unique_together = ("name", "related_name") 
+2
source

All Articles